numerus/pkg/router.go

52 lines
1.4 KiB
Go
Raw Normal View History

package pkg
import (
"context"
"html/template"
"log"
"net/http"
"github.com/jackc/pgx/v4/pgxpool"
)
func NewRouter(db *pgxpool.Pool) http.Handler {
router := http.NewServeMux()
router.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
email := r.FormValue("email")
password := r.FormValue("password")
var role string
if _, err := db.Exec(context.Background(), "select set_config('search_path', 'numerus, public', false)"); err != nil {
log.Printf("ERROR - %s", err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err := db.QueryRow(context.Background(), "select login($1, $2)", email, password).Scan(&role)
if err != nil {
log.Printf("ERROR - %s", err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte(role))
})
router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
t, err := template.ParseFiles("web/template/index.html")
if err != nil {
log.Printf("ERROR - %s", err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = t.Execute(w, nil)
if err != nil {
log.Printf("ERROR - %s", err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
})
var handler http.Handler = router
handler = Logger(handler)
return handler
}