Refactoring into view

This commit is contained in:
Chris Mann 2023-07-21 06:37:18 +02:00
parent f21f0ad727
commit ade1fada32
4 changed files with 69 additions and 53 deletions

View file

@ -1,5 +1,5 @@
BIN=guichet
SRC=main.go ssha.go profile.go admin.go invite.go directory.go utils.go picture.go login.go config.go
SRC=main.go ssha.go profile.go admin.go invite.go directory.go utils.go picture.go login.go config.go http-utils.go view/home.go
DOCKER=lxpz/guichet_amd64
all: $(BIN)

37
http-utils.go Normal file
View file

@ -0,0 +1,37 @@
/*
http-utils provide utility functions that interact with http
*/
package main
import (
"crypto/tls"
"net/http"
"github.com/go-ldap/ldap/v3"
)
func logRequest(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// log.Printf("%s %s %s\n", r.RemoteAddr, r.Method, r.URL)
handler.ServeHTTP(w, r)
})
}
func ldapOpen(w http.ResponseWriter) *ldap.Conn {
l, err := ldap.DialURL(config.LdapServerAddr)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return nil
}
if config.LdapTLS {
err = l.StartTLS(&tls.Config{InsecureSkipVerify: true})
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return nil
}
}
return l
}

53
main.go
View file

@ -7,7 +7,7 @@ package main
import (
"crypto/rand"
"crypto/tls"
// "crypto/tls"
// "encoding/json"
"flag"
@ -20,7 +20,6 @@ import (
// "os"
"strings"
"github.com/go-ldap/ldap/v3"
"github.com/gorilla/mux"
"github.com/gorilla/sessions"
)
@ -90,53 +89,3 @@ func main() {
log.Fatal("Cannot start http server: ", err)
}
}
func logRequest(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// log.Printf("%s %s %s\n", r.RemoteAddr, r.Method, r.URL)
handler.ServeHTTP(w, r)
})
}
func ldapOpen(w http.ResponseWriter) *ldap.Conn {
l, err := ldap.DialURL(config.LdapServerAddr)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return nil
}
if config.LdapTLS {
err = l.StartTLS(&tls.Config{InsecureSkipVerify: true})
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return nil
}
}
return l
}
// Page handlers ----
type HomePageData struct {
Login *LoginStatus
BaseDN string
Org string
}
func handleHome(w http.ResponseWriter, r *http.Request) {
templateHome := getTemplate("home.html")
login := checkLogin(w, r)
if login == nil {
return
}
data := &HomePageData{
Login: login,
BaseDN: config.BaseDN,
Org: config.Org,
}
templateHome.Execute(w, data)
}

30
view/home.go Normal file
View file

@ -0,0 +1,30 @@
/*
home show the home page
*/
package main
import "net/http"
type HomePageData struct {
Login *LoginStatus
BaseDN string
Org string
}
func handleHome(w http.ResponseWriter, r *http.Request) {
templateHome := getTemplate("home.html")
login := checkLogin(w, r)
if login == nil {
return
}
data := &HomePageData{
Login: login,
BaseDN: config.BaseDN,
Org: config.Org,
}
templateHome.Execute(w, data)
}