numerus/pkg/router/router.go

53 lines
1.4 KiB
Go
Raw Normal View History

package router
import (
"context"
"html/template"
"log"
"net/http"
"dev.tandem.ws/tandem/numerus/pkg/logger"
"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.Logger(handler)
return handler
}