rove/pkg/server/router.go

82 lines
1.8 KiB
Go
Raw Normal View History

package server
import (
"fmt"
2020-06-04 17:21:23 +01:00
"io"
"net/http"
)
2020-06-04 17:21:23 +01:00
// RequestHandler describes a function that handles any incoming request and can respond
type RequestHandler func(io.ReadCloser, io.Writer) error
2020-06-02 15:54:22 +01:00
// Route defines the information for a single path->function route
type Route struct {
path string
2020-06-04 17:21:23 +01:00
method string
handler RequestHandler
}
2020-06-04 17:23:27 +01:00
// requestHandlerHTTP wraps a request handler in http checks
func requestHandlerHTTP(method string, handler RequestHandler) func(w http.ResponseWriter, r *http.Request) {
2020-06-04 17:21:23 +01:00
return func(w http.ResponseWriter, r *http.Request) {
// Log the request
fmt.Printf("%s\t%s\n", r.Method, r.RequestURI)
// Verify we're hit with the right method
if r.Method != method {
w.WriteHeader(http.StatusMethodNotAllowed)
} else if err := handler(r.Body, w); err != nil {
// Log the error
fmt.Printf("Failed to handle http request: %s", err)
// Respond that we've had an error
w.WriteHeader(http.StatusInternalServerError)
} else {
// Be a good citizen and set the header for the return
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
}
}
2020-06-02 15:54:22 +01:00
}
// NewRouter sets up the server mux
func (s *Server) SetUpRouter() {
2020-06-02 15:54:22 +01:00
// Array of all our routes
var routes = []Route{
{
path: "/status",
2020-06-04 17:21:23 +01:00
method: http.MethodGet,
2020-06-02 15:54:22 +01:00
handler: s.HandleStatus,
},
{
path: "/register",
2020-06-04 17:21:23 +01:00
method: http.MethodPost,
2020-06-02 15:54:22 +01:00
handler: s.HandleRegister,
},
{
path: "/spawn",
2020-06-04 17:21:23 +01:00
method: http.MethodPost,
handler: s.HandleSpawn,
},
{
path: "/commands",
2020-06-04 17:21:23 +01:00
method: http.MethodPost,
handler: s.HandleCommands,
},
2020-06-04 16:57:38 +01:00
{
path: "/view",
2020-06-04 17:21:23 +01:00
method: http.MethodPost,
2020-06-04 16:57:38 +01:00
handler: s.HandleView,
},
2020-06-02 15:54:22 +01:00
}
// Set up the handlers
2020-06-02 15:54:22 +01:00
for _, route := range routes {
2020-06-04 17:23:27 +01:00
s.router.HandleFunc(route.path, requestHandlerHTTP(route.method, route.handler))
}
2020-06-04 16:57:38 +01:00
}