speed-tester/routes/base.go

63 lines
1.2 KiB
Go

package routes
import (
"net/http"
"strings"
"gitea.zokki.net/zokki/speed-tester/view"
)
type Route struct {
Path string
Get func(http.ResponseWriter, *http.Request)
Post func(http.ResponseWriter, *http.Request)
Put func(http.ResponseWriter, *http.Request)
Delete func(http.ResponseWriter, *http.Request)
Options func(http.ResponseWriter, *http.Request)
SubRoutes []*Route
}
type MethodsMap map[string]func(http.ResponseWriter, *http.Request)
type RoutesMap map[string]MethodsMap
func Routes() func(http.ResponseWriter, *http.Request) {
routesMap := routesToMap("/", &Route{
Get: render(view.Index),
SubRoutes: []*Route{
{
Path: "/data",
Get: allRoute,
SubRoutes: []*Route{
{
Path: "/speed",
Get: speedRoute,
},
{
Path: "/latency",
Get: latencyRoute,
},
{
Path: "/duration",
Get: durationRoute,
},
},
},
},
})
return func(writer http.ResponseWriter, req *http.Request) {
path := req.URL.Path
if path != "/" {
path = strings.TrimSuffix(path, "/")
}
handler := routesMap[path][req.Method]
if handler == nil {
http.NotFound(writer, req)
return
}
handler(writer, req)
}
}