controller.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package pairec
  2. import (
  3. "fmt"
  4. "io"
  5. "net/http"
  6. "runtime/debug"
  7. "strings"
  8. "gitlab.alibaba-inc.com/pai_biz_arch/pairec/log"
  9. )
  10. type ControllerInterface interface {
  11. Process(http.ResponseWriter, *http.Request)
  12. }
  13. type ControllerRegister struct {
  14. routeInfos map[string]*RouteInfo
  15. }
  16. func NewControllerRegister() *ControllerRegister {
  17. cr := &ControllerRegister{
  18. routeInfos: make(map[string]*RouteInfo),
  19. }
  20. return cr
  21. }
  22. func (c *ControllerRegister) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
  23. defer func() {
  24. if err := recover(); err != nil {
  25. stack := string(debug.Stack())
  26. log.Error(fmt.Sprintf("error=%v, stack=%s", err, strings.ReplaceAll(stack, "\n", "\t")))
  27. Error(rw, 500, "server error")
  28. }
  29. }()
  30. uri := req.RequestURI
  31. if index := strings.Index(req.RequestURI, "?"); index != -1 {
  32. uri = req.RequestURI[:index]
  33. }
  34. if info, exist := c.routeInfos[uri]; exist {
  35. if info.initialize != nil {
  36. c := info.initialize()
  37. c.Process(rw, req)
  38. } else if info.hf != nil {
  39. info.hf(rw, req)
  40. } else {
  41. // return 404
  42. Error(rw, 404, "controller not found")
  43. return
  44. }
  45. } else {
  46. // return 404
  47. Error(rw, 404, "url not found route info")
  48. return
  49. }
  50. }
  51. func (c *ControllerRegister) Register(routeInfo *RouteInfo) {
  52. c.routeInfos[routeInfo.pattern] = routeInfo
  53. }
  54. func Error(rw http.ResponseWriter, code int, msg string) {
  55. rw.WriteHeader(code)
  56. io.WriteString(rw, msg)
  57. }