Compare commits

..

No commits in common. "759c274950a88dd0f9ab812a910507362871afbd" and "6e1640e4b4b6169d9b25ad2ebc87513f1601eb18" have entirely different histories.

6 changed files with 60 additions and 80 deletions

View file

@ -1,13 +1,13 @@
package api
import (
"encoding/json"
"errors"
"net/http"
"dynatron.me/x/stillbox/pkg/talkgroups"
"github.com/go-chi/chi/v5"
"github.com/go-chi/render"
"github.com/go-viper/mapstructure/v2"
"github.com/jackc/pgx/v5"
"github.com/rs/zerolog/log"
@ -29,81 +29,57 @@ func New() API {
func (a *api) Subrouter() http.Handler {
r := chi.NewMux()
r.Mount("/talkgroup", new(talkgroupAPI).Subrouter())
r.Mount("/talkgroup", new(talkgroupAPI).routes())
return r
}
type errResponse struct {
Err error `json:"-"`
Code int `json:"-"`
Error string `json:"error"`
text string
code int
}
func (e *errResponse) Render(w http.ResponseWriter, r *http.Request) error {
switch e.Code {
case http.StatusNotFound:
case http.StatusBadRequest:
default:
log.Error().Str("path", r.URL.Path).Err(e.Err).Int("code", e.Code).Str("msg", e.Error).Msg("request failed")
var statusMapping = map[error]errResponse{
talkgroups.ErrNotFound: {talkgroups.ErrNotFound.Error(), http.StatusNotFound},
pgx.ErrNoRows: {"no such record", http.StatusNotFound},
}
render.Status(r, e.Code)
return nil
}
func badRequest(err error) render.Renderer {
return &errResponse{
Err: err,
Code: http.StatusBadRequest,
Error: "Bad request",
}
}
func recordNotFound(err error) render.Renderer {
return &errResponse{
Err: err,
Code: http.StatusNotFound,
Error: "Record not found",
}
}
func internalError(err error) render.Renderer {
return &errResponse{
Err: err,
Code: http.StatusNotFound,
Error: "Internal server error",
}
}
type errResponder func(error) render.Renderer
var statusMapping = map[error]errResponder{
talkgroups.ErrNotFound: recordNotFound,
pgx.ErrNoRows: recordNotFound,
}
func autoError(err error) render.Renderer {
func httpCode(err error) (string, int) {
c, ok := statusMapping[err]
if ok {
c(err)
return c.text, c.code
}
for e, c := range statusMapping { // check if err wraps an error we know about
if errors.Is(err, e) {
return c(err)
return c.text, c.code
}
}
return internalError(err)
return err.Error(), http.StatusInternalServerError
}
func wErr(w http.ResponseWriter, r *http.Request, v render.Renderer) {
err := render.Render(w, r, v)
func writeResponse(w http.ResponseWriter, r *http.Request, data interface{}, err error) {
if err != nil {
log.Error().Err(err).Msg("wErr render error")
log.Error().Str("path", r.URL.Path).Err(err).Msg("request failed")
text, code := httpCode(err)
http.Error(w, text, code)
return
}
w.Header().Set("Content-Type", "application/json")
enc := json.NewEncoder(w)
err = enc.Encode(data)
if err != nil {
log.Error().Str("path", r.URL.Path).Err(err).Msg("response marshal failed")
text, code := httpCode(err)
http.Error(w, text, code)
return
}
}
func reqErr(w http.ResponseWriter, err error, code int) {
http.Error(w, err.Error(), code)
}
func decodeParams(d interface{}, r *http.Request) error {
@ -127,6 +103,6 @@ func decodeParams(d interface{}, r *http.Request) error {
return dec.Decode(m)
}
func respond(w http.ResponseWriter, r *http.Request, v interface{}) {
render.DefaultResponder(w, r, v)
func badReq(w http.ResponseWriter, err error) {
reqErr(w, err, http.StatusBadRequest)
}

View file

@ -1,6 +1,7 @@
package api
import (
"encoding/json"
"net/http"
"dynatron.me/x/stillbox/internal/forms"
@ -13,7 +14,7 @@ import (
type talkgroupAPI struct {
}
func (tga *talkgroupAPI) Subrouter() http.Handler {
func (tga *talkgroupAPI) routes() http.Handler {
r := chi.NewMux()
r.Get("/{system:\\d+}/{id:\\d+}", tga.talkgroup)
@ -56,7 +57,7 @@ func (tga *talkgroupAPI) talkgroup(w http.ResponseWriter, r *http.Request) {
err := decodeParams(&p, r)
if err != nil {
wErr(w, r, badRequest(err))
badReq(w, err)
return
}
@ -70,19 +71,14 @@ func (tga *talkgroupAPI) talkgroup(w http.ResponseWriter, r *http.Request) {
res, err = tgs.TGs(ctx, nil)
}
if err != nil {
wErr(w, r, autoError(err))
return
}
respond(w, r, res)
writeResponse(w, r, res, err)
}
func (tga *talkgroupAPI) putTalkgroup(w http.ResponseWriter, r *http.Request) {
var id tgParams
err := decodeParams(&id, r)
if err != nil {
wErr(w, r, badRequest(err))
badReq(w, err)
return
}
@ -93,16 +89,19 @@ func (tga *talkgroupAPI) putTalkgroup(w http.ResponseWriter, r *http.Request) {
err = forms.Unmarshal(r, &input, forms.WithTag("json"), forms.WithAcceptBlank(), forms.WithOmitEmpty())
if err != nil {
wErr(w, r, badRequest(err))
writeResponse(w, r, nil, err)
return
}
input.ID = id.ToID().Pack()
record, err := tgs.UpdateTG(ctx, input)
if err != nil {
wErr(w, r, autoError(err))
writeResponse(w, r, nil, err)
return
}
respond(w, r, record)
err = json.NewEncoder(w).Encode(record)
if err != nil {
writeResponse(w, r, nil, err)
}
}

View file

@ -56,13 +56,13 @@ func NewClient(ctx context.Context, conf config.DB) (*DB, error) {
return db, nil
}
type dBCtxKey string
type DBCtxKey string
const DBCtxKey dBCtxKey = "dbctx"
const DBCtxKeyValue DBCtxKey = "dbctx"
// FromCtx returns the database handle from the provided Context.
func FromCtx(ctx context.Context) *DB {
c, ok := ctx.Value(DBCtxKey).(*DB)
c, ok := ctx.Value(DBCtxKeyValue).(*DB)
if !ok {
panic("no DB in context")
}
@ -72,7 +72,7 @@ func FromCtx(ctx context.Context) *DB {
// CtxWithDB returns a Context with the provided database handle.
func CtxWithDB(ctx context.Context, conn *DB) context.Context {
return context.WithValue(ctx, DBCtxKey, conn)
return context.WithValue(ctx, DBCtxKeyValue, conn)
}
// IsNoRows is a convenience function that returns whether a returned error is a database

View file

@ -4,9 +4,14 @@
package server
import (
"github.com/go-chi/chi/v5/middleware"
"net/http/pprof"
)
func (s *Server) installPprof() {
s.r.Mount("/debug", middleware.Profiler())
r := s.r
r.HandleFunc("/debug/pprof/", pprof.Index)
r.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
r.HandleFunc("/debug/pprof/profile", pprof.Profile)
r.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
r.HandleFunc("/debug/pprof/trace", pprof.Trace)
}

View file

@ -27,8 +27,8 @@ func (s *Server) setupRoutes() {
}
r := s.r
r.Use(middleware.WithValue(database.DBCtxKey, s.db))
r.Use(middleware.WithValue(talkgroups.StoreCtxKey, s.tgs))
r.Use(middleware.WithValue(database.DBCtxKeyValue, s.db))
r.Use(middleware.WithValue(talkgroups.StoreCtxKeyValue, s.tgs))
s.installPprof()

View file

@ -57,16 +57,16 @@ type Store interface {
HUP(*config.Config)
}
type storeCtxKey string
type CtxStoreKey string
const StoreCtxKey storeCtxKey = "store"
const StoreCtxKeyValue CtxStoreKey = "store"
func CtxWithStore(ctx context.Context, s Store) context.Context {
return context.WithValue(ctx, StoreCtxKey, s)
return context.WithValue(ctx, StoreCtxKeyValue, s)
}
func StoreFrom(ctx context.Context) Store {
s, ok := ctx.Value(StoreCtxKey).(Store)
s, ok := ctx.Value(StoreCtxKeyValue).(Store)
if !ok {
return NewCache()
}