added multiple method support for routes
This commit is contained in:
@@ -4,11 +4,15 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"slices"
|
||||
)
|
||||
|
||||
type Route struct {
|
||||
Path string // Absolute path to the requested resource
|
||||
Method Method // HTTP Method
|
||||
Path string // Absolute path to the requested resource
|
||||
Method Method // HTTP Method
|
||||
// Methods is an optional slice of Methods to use, if more than one can use the same handler.
|
||||
// Will take precedence over the Method field if provided
|
||||
Methods []Method
|
||||
Handler http.Handler // Handler to use for the request
|
||||
}
|
||||
|
||||
@@ -28,21 +32,33 @@ const (
|
||||
|
||||
// Server.AddRoutes registers the page handlers for the server.
|
||||
// At least one route must be provided.
|
||||
// If any route patterns (path + method) are defined multiple times, the first
|
||||
// instance will be added and any additional conflicts will be discarded.
|
||||
func (server *Server) AddRoutes(routes ...Route) error {
|
||||
if len(routes) == 0 {
|
||||
return errors.New("No routes provided")
|
||||
}
|
||||
patterns := []string{}
|
||||
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 len(route.Methods) == 0 {
|
||||
route.Methods = []Method{route.Method}
|
||||
}
|
||||
if route.Handler == nil {
|
||||
return fmt.Errorf("No handler provided for %s %s", route.Method, route.Path)
|
||||
for _, method := range route.Methods {
|
||||
if !validMethod(method) {
|
||||
return fmt.Errorf("Invalid method %s for path %s", method, route.Path)
|
||||
}
|
||||
if route.Handler == nil {
|
||||
return fmt.Errorf("No handler provided for %s %s", method, route.Path)
|
||||
}
|
||||
pattern := fmt.Sprintf("%s %s", method, route.Path)
|
||||
if slices.Contains(patterns, pattern) {
|
||||
continue
|
||||
}
|
||||
patterns = append(patterns, pattern)
|
||||
mux.Handle(pattern, route.Handler)
|
||||
}
|
||||
pattern := fmt.Sprintf("%s %s", route.Method, route.Path)
|
||||
mux.Handle(pattern, route.Handler)
|
||||
}
|
||||
|
||||
server.server.Handler = mux
|
||||
|
||||
Reference in New Issue
Block a user