method.go 795 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package ss
  2. // The type implements method routing.
  3. type MethodRouter struct {
  4. methodMap map[ReqMethod] Handler
  5. def Handler
  6. }
  7. // Returns new empty MethodRouter.
  8. func Method(def Handler) *MethodRouter {
  9. ret := &MethodRouter{}
  10. ret.methodMap = make(map[ReqMethod]Handler)
  11. ret.def = def
  12. return ret
  13. }
  14. // Define new handler for the specified method.
  15. func (mr *MethodRouter) Case(
  16. method ReqMethod,
  17. handler Handler,
  18. ) *MethodRouter {
  19. _, dup := mr.methodMap[method]
  20. if dup {
  21. panic("got the duplicate method")
  22. }
  23. mr.methodMap[method] = handler
  24. return mr
  25. }
  26. // Implementing the Handler.
  27. func (mr *MethodRouter) Handle(c *Context) {
  28. handler, ok := mr.methodMap[c.Method()]
  29. if !ok {
  30. if mr.def == nil {
  31. c.NotFound()
  32. } else {
  33. mr.def.Handle(c)
  34. }
  35. return
  36. }
  37. handler.Handle(c)
  38. }