gohttpserver/internal/handlers/handlers.go

54 lines
1.2 KiB
Go
Raw Normal View History

2022-11-28 03:59:20 +00:00
package handlers
import (
"context"
"encoding/json"
"net/http"
2022-11-28 04:09:23 +00:00
"git.eeqj.de/sneak/gohttpserver/internal/database"
2022-11-28 03:59:20 +00:00
"git.eeqj.de/sneak/gohttpserver/internal/globals"
2022-11-28 04:09:23 +00:00
"git.eeqj.de/sneak/gohttpserver/internal/logger"
2022-11-28 03:59:20 +00:00
"github.com/rs/zerolog"
"go.uber.org/fx"
)
type HandlersParams struct {
fx.In
2022-11-28 04:09:23 +00:00
Logger logger.Logger
2022-11-28 03:59:20 +00:00
Globals globals.Globals
Database database.Database
}
type Handlers struct {
params HandlersParams
log *zerolog.Logger
}
func New(lc fx.Lifecycle, params HandlersParams) (*Handlers, error) {
s := new(Handlers)
s.params = params
s.log = params.Logger.Get()
lc.Append(fx.Hook{
OnStart: func(ctx context.Context) error {
// FIXME compile some templates here or something
2022-11-28 04:09:23 +00:00
return nil
2022-11-28 03:59:20 +00:00
},
})
return s, nil
}
func (s *Handlers) respondJSON(w http.ResponseWriter, r *http.Request, data interface{}, status int) {
w.WriteHeader(status)
w.Header().Set("Content-Type", "application/json")
if data != nil {
err := json.NewEncoder(w).Encode(data)
if err != nil {
s.log.Error().Err(err).Msg("json encode error")
}
}
}
func (s *Handlers) decodeJSON(w http.ResponseWriter, r *http.Request, v interface{}) error { // nolint
return json.NewDecoder(r.Body).Decode(v)
}