fix: refactor code to be testable #181
This commit was merged in pull request #212.
This commit is contained in:
57
handler/index_and_404.go
Normal file
57
handler/index_and_404.go
Normal file
@@ -0,0 +1,57 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"me-fit/service"
|
||||
"me-fit/template"
|
||||
"me-fit/types"
|
||||
"me-fit/utils"
|
||||
|
||||
"database/sql"
|
||||
"net/http"
|
||||
|
||||
"github.com/a-h/templ"
|
||||
)
|
||||
|
||||
type IndexHandler interface {
|
||||
handle(router *http.ServeMux)
|
||||
}
|
||||
|
||||
type IndexHandlerImpl struct {
|
||||
db *sql.DB
|
||||
service service.AuthService
|
||||
serverSettings *types.ServerSettings
|
||||
}
|
||||
|
||||
func NewIndexHandler(db *sql.DB, service service.AuthService, serverSettings *types.ServerSettings) IndexHandler {
|
||||
return IndexHandlerImpl{
|
||||
db: db,
|
||||
service: service,
|
||||
serverSettings: serverSettings,
|
||||
}
|
||||
}
|
||||
|
||||
func (handler IndexHandlerImpl) handle(router *http.ServeMux) {
|
||||
router.Handle("/", handler.handleIndexAnd404())
|
||||
}
|
||||
|
||||
func (handler IndexHandlerImpl) handleIndexAnd404() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
user, err := handler.service.GetUserFromSessionId(utils.GetSessionID(r))
|
||||
|
||||
var comp templ.Component = nil
|
||||
userComp := service.UserInfoComp(user)
|
||||
|
||||
if r.URL.Path != "/" {
|
||||
comp = template.Layout(template.NotFound(), userComp, handler.serverSettings.Environment)
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
} else {
|
||||
comp = template.Layout(template.Index(), userComp, handler.serverSettings.Environment)
|
||||
}
|
||||
|
||||
err = comp.Render(r.Context(), w)
|
||||
if err != nil {
|
||||
utils.LogError("Failed to render index", err)
|
||||
http.Error(w, "Failed to render index", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user