Files
image-storage/server.go

70 lines
1.4 KiB
Go

package main
import (
"encoding/json"
"net/http"
)
type ApiError struct {
Message string `json:"message"`
Err error `json:"error"`
Status int
}
func (a *ApiError) Error() string {
return a.Message
}
type Server struct {
addr string
mux *http.ServeMux
}
func NewServer(addr string) *Server {
return &Server{
addr: addr,
mux: http.NewServeMux(),
}
}
func (s *Server) Handle(pattern string, handler func(w http.ResponseWriter, r *http.Request) error) {
s.mux.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
err := handler(w, r)
if err != nil {
if e, ok := err.(*ApiError); ok {
var nestedErr *string
if e.Err != nil {
nestedErr = new(e.Err.Error())
}
s.JSON(w, map[string]any{
"message": e.Message,
"error": nestedErr,
}, e.Status)
} else {
s.JSON(w, map[string]any{
"message": "something bad happened",
"error": err.Error(),
}, 500)
}
}
})
}
func (s *Server) JSON(w http.ResponseWriter, data any, status int) error {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
return json.NewEncoder(w).Encode(data)
}
func (s *Server) Error(msg string, err error, status int) error {
return &ApiError{
Message: msg,
Err: err,
Status: status,
}
}
func (s *Server) ListenAndServe() error {
return http.ListenAndServe(s.addr, s.mux)
}