init
This commit is contained in:
49
router/router.go
Normal file
49
router/router.go
Normal file
@@ -0,0 +1,49 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type router struct {
|
||||
mux *http.ServeMux
|
||||
}
|
||||
|
||||
func (router *router) Mux() *http.ServeMux {
|
||||
return router.mux
|
||||
}
|
||||
|
||||
func (router *router) MsgError(msg string, err error) string {
|
||||
m := msg
|
||||
if err != nil {
|
||||
m = fmt.Sprintf("%s: %v", msg, err)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func (router *router) SendJSON(w http.ResponseWriter, data any) error {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if err := json.NewEncoder(w).Encode(data); err != nil {
|
||||
return fmt.Errorf("something bad happened: %v", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (router *router) Handle(pattern string, handler func(w http.ResponseWriter, r *http.Request) error) {
|
||||
router.mux.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
|
||||
if err := handler(w, r); err != nil {
|
||||
router.SendJSON(w, struct {
|
||||
Error string `json:"error"`
|
||||
}{
|
||||
Error: err.Error(),
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func New() *router {
|
||||
return &router{
|
||||
mux: http.NewServeMux(),
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user