Matthew Stobbs
77c34481ce
- instead of having to make a new type for each set of routes, now we just need to define the routes as an exported variable. - TODO: add a mechanism to add routes externally to the server setup
58 lines
2.0 KiB
Go
58 lines
2.0 KiB
Go
package router
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
|
|
"git.staur.ca/stobbsm/clustvirt/cluster"
|
|
"git.staur.ca/stobbsm/clustvirt/lib/log"
|
|
)
|
|
|
|
type Routes []Route
|
|
|
|
func addprefix(b, p string) string { return fmt.Sprintf("%s%s", b, p) }
|
|
func trace(p string) string { return fmt.Sprintf("TRACE %s", p) }
|
|
func options(p string) string { return fmt.Sprintf("OPTIONS %s", p) }
|
|
func connect(p string) string { return fmt.Sprintf("CONNECT %s", p) }
|
|
func head(p string) string { return fmt.Sprintf("HEAD %s", p) }
|
|
func get(p string) string { return fmt.Sprintf("GET %s", p) }
|
|
func post(p string) string { return fmt.Sprintf("POST %s", p) }
|
|
func put(p string) string { return fmt.Sprintf("PUT %s", p) }
|
|
func patch(p string) string { return fmt.Sprintf("PATCH %s", p) }
|
|
func delete(p string) string { return fmt.Sprintf("DELETE %s", p) }
|
|
|
|
func (rte Routes) MountTo(prefix string, c *cluster.Cluster, mux *http.ServeMux) error {
|
|
var errs []error
|
|
for _, r := range rte {
|
|
switch r.Method {
|
|
case http.MethodTrace:
|
|
mux.Handle(trace(addprefix(prefix, r.Path)), r.Handler(c))
|
|
case http.MethodOptions:
|
|
mux.Handle(options(addprefix(prefix, r.Path)), r.Handler(c))
|
|
case http.MethodConnect:
|
|
mux.Handle(connect(addprefix(prefix, r.Path)), r.Handler(c))
|
|
case http.MethodHead:
|
|
mux.Handle(head(addprefix(prefix, r.Path)), r.Handler(c))
|
|
case http.MethodGet:
|
|
mux.Handle(get(addprefix(prefix, r.Path)), r.Handler(c))
|
|
case http.MethodPost:
|
|
mux.Handle(post(addprefix(prefix, r.Path)), r.Handler(c))
|
|
case http.MethodPut:
|
|
mux.Handle(put(addprefix(prefix, r.Path)), r.Handler(c))
|
|
case http.MethodPatch:
|
|
mux.Handle(patch(addprefix(prefix, r.Path)), r.Handler(c))
|
|
case http.MethodDelete:
|
|
mux.Handle(delete(addprefix(prefix, r.Path)), r.Handler(c))
|
|
default:
|
|
mux.Handle(addprefix(prefix, r.Path), r.Handler(c))
|
|
}
|
|
log.Info("Routes.MoutnTo").
|
|
Str("prefix", prefix).
|
|
Str("Route.Path", r.Path).
|
|
Str("Route.Method", r.Method).
|
|
Msg("route registered")
|
|
}
|
|
return errors.Join(errs...)
|
|
}
|