package hws import ( "errors" "fmt" "net/http" ) type Route struct { Path string // Absolute path to the requested resource Method Method // HTTP Method Handler http.Handler // Handler to use for the request } type Method string const ( MethodGET Method = "GET" MethodPOST Method = "POST" MethodPUT Method = "PUT" MethodHEAD Method = "HEAD" MethodDELETE Method = "DELETE" MethodCONNECT Method = "CONNECT" MethodOPTIONS Method = "OPTIONS" MethodTRACE Method = "TRACE" MethodPATCH Method = "PATCH" ) // Server.AddRoutes registers the page handlers for the server. // At least one route must be provided. func (server *Server) AddRoutes(routes ...Route) error { if len(routes) == 0 { return errors.New("No routes provided") } mux := http.NewServeMux() mux.HandleFunc("GET /healthz", func(http.ResponseWriter, *http.Request) {}) for _, route := range routes { if !validMethod(route.Method) { return fmt.Errorf("Invalid method %s for path %s", route.Method, route.Path) } if route.Handler == nil { return fmt.Errorf("No handler provided for %s %s", route.Method, route.Path) } pattern := fmt.Sprintf("%s %s", route.Method, route.Path) mux.Handle(pattern, route.Handler) } server.server.Handler = mux server.routes = true return nil } func validMethod(m Method) bool { switch m { case MethodGET, MethodPOST, MethodPUT, MethodHEAD, MethodDELETE, MethodCONNECT, MethodOPTIONS, MethodTRACE, MethodPATCH: return true default: return false } }