ss/method.go

44 lines
795 B
Go
Raw Permalink Normal View History

2024-05-19 20:48:06 +03:00
package ss
// The type implements method routing.
type MethodRouter struct {
methodMap map[ReqMethod] Handler
def Handler
}
// Returns new empty MethodRouter.
2024-05-19 20:48:06 +03:00
func Method(def Handler) *MethodRouter {
ret := &MethodRouter{}
ret.methodMap = make(map[ReqMethod]Handler)
2024-05-19 20:48:06 +03:00
ret.def = def
return ret
}
// Define new handler for the specified method.
func (mr *MethodRouter) Case(
method ReqMethod,
handler Handler,
) *MethodRouter {
_, dup := mr.methodMap[method]
if dup {
panic("got the duplicate method")
}
mr.methodMap[method] = handler
return mr
}
// Implementing the Handler.
func (mr *MethodRouter) Handle(c *Context) {
handler, ok := mr.methodMap[c.Method()]
if !ok {
if mr.def == nil {
c.NotFound()
} else {
mr.def.Handle(c)
}
return
}
handler.Handle(c)
}