init
This commit is contained in:
51
server.go
Normal file
51
server.go
Normal 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)
|
||||
}
|
||||
Reference in New Issue
Block a user