use Chi Router instead of Chi Mux.

This commit is contained in:
Miroslav Šedivý 2020-11-14 18:16:25 +01:00
parent a18482b54e
commit 40b986c8be
7 changed files with 13 additions and 143 deletions

View File

@ -20,8 +20,6 @@ func New(
} }
} }
func (h *MemberHandler) Router() *chi.Mux { func (h *MemberHandler) Route(r chi.Router) {
r := chi.NewRouter()
return r
} }

View File

@ -26,9 +26,7 @@ func New(
} }
} }
func (h *RoomHandler) Router() *chi.Mux { func (h *RoomHandler) Route(r chi.Router) {
r := chi.NewRouter()
// TODO: Authorizaton. // TODO: Authorizaton.
r.Route("/screen", func(r chi.Router) { r.Route("/screen", func(r chi.Router) {
r.Get("/", h.ScreenConfiguration) r.Get("/", h.ScreenConfiguration)
@ -41,6 +39,4 @@ func (h *RoomHandler) Router() *chi.Mux {
r.Get("/", h.ClipboardRead) r.Get("/", h.ClipboardRead)
r.Post("/", h.ClipboardWrite) r.Post("/", h.ClipboardWrite)
}) })
return r
} }

View File

@ -37,14 +37,14 @@ func New(
} }
} }
func (api *ApiManagerCtx) Mount(r *chi.Mux) { func (api *ApiManagerCtx) Route(r chi.Router) {
r.Use(api.Authenticate) r.Use(api.Authenticate)
memberHandler := member.New(api.sessions) memberHandler := member.New(api.sessions)
r.Mount("/member", memberHandler.Router()) r.Route("/member", memberHandler.Route)
roomHandler := room.New(api.sessions, api.desktop, api.capture) roomHandler := room.New(api.sessions, api.desktop, api.capture)
r.Mount("/room", roomHandler.Router()) r.Route("/room", roomHandler.Route)
r.Get("/test", func(w http.ResponseWriter, r *http.Request) { r.Get("/test", func(w http.ResponseWriter, r *http.Request) {
session, _ := r.Context().Value(keySessionCtx).(types.Session) session, _ := r.Context().Value(keySessionCtx).(types.Session)

View File

@ -1,101 +0,0 @@
package endpoint
import (
"encoding/json"
"fmt"
"net/http"
"runtime/debug"
"github.com/go-chi/chi/middleware"
"github.com/rs/zerolog/log"
)
type (
Endpoint func(http.ResponseWriter, *http.Request) error
ErrResponse struct {
Status int `json:"status,omitempty"`
Err string `json:"error,omitempty"`
Message string `json:"message,omitempty"`
Details string `json:"details,omitempty"`
Code string `json:"code,omitempty"`
RequestID string `json:"request,omitempty"`
}
)
func Handle(handler Endpoint) http.HandlerFunc {
fn := func(w http.ResponseWriter, r *http.Request) {
if err := handler(w, r); err != nil {
WriteError(w, r, err)
}
}
return http.HandlerFunc(fn)
}
var nonErrorsCodes = map[int]bool{
404: true,
}
func errResponse(input interface{}) *ErrResponse {
var res *ErrResponse
var err interface{}
//nolint
switch input.(type) {
case *HandlerError:
e := input.(*HandlerError)
res = &ErrResponse{
Status: e.Status,
Err: http.StatusText(e.Status),
Message: e.Message,
}
err = e.Err
default:
res = &ErrResponse{
Status: http.StatusInternalServerError,
Err: http.StatusText(http.StatusInternalServerError),
}
err = input
}
if err != nil {
switch err.(type) {
case *error:
e := err.(error)
res.Details = e.Error()
default:
res.Details = fmt.Sprintf("%+v", err)
}
}
return res
}
func WriteError(w http.ResponseWriter, r *http.Request, err interface{}) {
hlog := log.With().
Str("module", "http").
Logger()
res := errResponse(err)
if reqID := middleware.GetReqID(r.Context()); reqID != "" {
res.RequestID = reqID
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(res.Status)
if err := json.NewEncoder(w).Encode(res); err != nil {
hlog.Warn().Err(err).Msg("Failed writing json error response")
}
if !nonErrorsCodes[res.Status] {
logEntry := middleware.GetLogEntry(r)
if logEntry != nil {
logEntry.Panic(err, debug.Stack())
} else {
hlog.Error().Str("stack", string(debug.Stack())).Msgf("%+v", err)
}
}
}

View File

@ -1,17 +0,0 @@
package endpoint
import "fmt"
type HandlerError struct {
Status int
Message string
Err error
}
func (e *HandlerError) Error() string {
if e.Err != nil {
return fmt.Sprintf("%s: %s", e.Message, e.Err.Error())
}
return e.Message
}

View File

@ -2,7 +2,6 @@ package http
import ( import (
"context" "context"
"fmt"
"net/http" "net/http"
"os" "os"
@ -13,7 +12,7 @@ import (
"demodesk/neko/internal/types" "demodesk/neko/internal/types"
"demodesk/neko/internal/config" "demodesk/neko/internal/config"
"demodesk/neko/internal/http/endpoint" "demodesk/neko/internal/utils"
) )
type HttpManagerCtx struct { type HttpManagerCtx struct {
@ -31,13 +30,11 @@ func New(WebSocketManager types.WebSocketManager, ApiManager types.ApiManager, c
router.Use(middleware.RequestID) // Create a request ID for each request router.Use(middleware.RequestID) // Create a request ID for each request
router.Use(Logger) // Log API request calls using custom logger function router.Use(Logger) // Log API request calls using custom logger function
ApiManager.Mount(router) router.Route("/api", ApiManager.Route)
router.Get("/ws", func(w http.ResponseWriter, r *http.Request) { router.Get("/ws", func(w http.ResponseWriter, r *http.Request) {
if WebSocketManager.Upgrade(w, r) != nil { //nolint
//nolint WebSocketManager.Upgrade(w, r)
w.Write([]byte("unable to upgrade your connection to a websocket"))
}
}) })
if conf.Static != "" { if conf.Static != "" {
@ -51,11 +48,8 @@ func New(WebSocketManager types.WebSocketManager, ApiManager types.ApiManager, c
}) })
} }
router.NotFound(endpoint.Handle(func(w http.ResponseWriter, r *http.Request) error { router.NotFound(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
return &endpoint.HandlerError{ utils.HttpNotFound(w)
Status: http.StatusNotFound,
Message: fmt.Sprintf("Endpoint '%s' was not found.", r.RequestURI),
}
})) }))
http := &http.Server{ http := &http.Server{

View File

@ -5,5 +5,5 @@ import (
) )
type ApiManager interface { type ApiManager interface {
Mount(r *chi.Mux) Route(r chi.Router)
} }