This commit is contained in:
2026-03-16 19:59:07 +03:00
commit c1935c8edb
8 changed files with 276 additions and 0 deletions

51
server.go Normal file
View File

@@ -0,0 +1,51 @@
package main
import (
"encoding/json"
"net/http"
)
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) {
if err := handler(w, r); err != nil {
s.Error(w, "something bad happened", err, 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(w http.ResponseWriter, msg string, err error, status int) {
var e *string
if err != nil {
e = new(err.Error())
}
s.JSON(w, struct {
Message string `json:"message"`
Error *string `json:"error"`
}{
Message: msg,
Error: e,
}, status)
}
func (s *Server) ListenAndServe() error {
return http.ListenAndServe(s.addr, s.mux)
}