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