package handlers import ( "context" "encoding/json" "net/http" "github.com/rs/zerolog" "go.uber.org/fx" "sneak.berlin/go/directory/internal/database" "sneak.berlin/go/directory/internal/globals" "sneak.berlin/go/directory/internal/healthcheck" "sneak.berlin/go/directory/internal/logger" ) type HandlersParams struct { fx.In Logger *logger.Logger Globals *globals.Globals Database *database.Database Healthcheck *healthcheck.Healthcheck } type Handlers struct { params *HandlersParams log *zerolog.Logger hc *healthcheck.Healthcheck } func New(lc fx.Lifecycle, params HandlersParams) (*Handlers, error) { s := new(Handlers) s.params = ¶ms s.log = params.Logger.Get() s.hc = params.Healthcheck lc.Append(fx.Hook{ OnStart: func(ctx context.Context) error { // FIXME compile some templates here or something return nil }, }) return s, nil } const jsonContentType = "application/json; charset=utf-8" func (s *Handlers) respondJSON(w http.ResponseWriter, r *http.Request, data interface{}, status int) { w.WriteHeader(status) w.Header().Set("Content-Type", jsonContentType) if data != nil { err := json.NewEncoder(w).Encode(data) if err != nil { s.log.Error().Err(err).Msg("json encode error") http.Error(w, err.Error(), http.StatusInternalServerError) } } } func (s *Handlers) decodeJSON(w http.ResponseWriter, r *http.Request, v interface{}) error { // nolint return json.NewDecoder(r.Body).Decode(v) }