62 lines
1.4 KiB
Go
62 lines
1.4 KiB
Go
|
package handlers
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"encoding/json"
|
||
|
"net/http"
|
||
|
"time"
|
||
|
|
||
|
"git.eeqj.de/sneak/gohttpserver/internal/globals"
|
||
|
"github.com/rs/zerolog"
|
||
|
"go.uber.org/fx"
|
||
|
"google.golang.org/genproto/googleapis/spanner/admin/database/v1"
|
||
|
)
|
||
|
|
||
|
type HandlersParams struct {
|
||
|
fx.In
|
||
|
Logger *zerolog.Logger
|
||
|
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
|
||
|
},
|
||
|
})
|
||
|
return s, nil
|
||
|
}
|
||
|
|
||
|
func (s *Handlers) HandleNow() http.HandlerFunc {
|
||
|
type response struct {
|
||
|
Now time.Time `json:"now"`
|
||
|
}
|
||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||
|
s.respondJSON(w, r, &response{Now: time.Now()}, 200)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
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)
|
||
|
}
|