bodytrack/api/internal/handlers/helpers.go

43 lines
846 B
Go

package handlers
import (
"encoding/json"
"net/http"
"github.com/go-chi/chi/v5"
)
type ApiHandler interface {
Subscribe(chi.Router) error
}
type APIResp struct {
Status int `json:"-"`
Success bool `json:"success"`
Payload interface{} `json:"payload"`
}
func (a APIResp) Write(res http.ResponseWriter) {
if a.Status != 0 {
res.WriteHeader(a.Status)
}
res.Header().Set("content-type", "application/json; utf-8")
enc := json.NewEncoder(res)
enc.SetIndent("\n", "\t")
enc.Encode(a)
}
func ParseCall(model interface{}, res http.ResponseWriter, req *http.Request) error {
defer req.Body.Close()
decoder := json.NewDecoder(req.Body)
decoder.DisallowUnknownFields()
if err := decoder.Decode(&model); err != nil {
a := APIResp{Success: false, Payload: err.Error()}
a.Write(res)
return err
}
return nil
}