controller.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package web
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "time"
  8. "gitlab.alibaba-inc.com/pai_biz_arch/pairec/log"
  9. )
  10. const (
  11. SUCCESS_CODE int = 200
  12. ERROR_PARAMETER_CODE int = 400
  13. SERVER_ERROR_CODE int = 500
  14. )
  15. var (
  16. CODE_MAPS = map[int]string{
  17. SUCCESS_CODE: "success",
  18. ERROR_PARAMETER_CODE: "parammeter error",
  19. SERVER_ERROR_CODE: "server error",
  20. }
  21. )
  22. type ErrorResponse struct {
  23. Response
  24. }
  25. func (e *ErrorResponse) ToString() string {
  26. j, _ := json.Marshal(e)
  27. return string(j)
  28. }
  29. type Controller struct {
  30. RequestBody []byte
  31. RequestId string
  32. Start time.Time
  33. End time.Time
  34. }
  35. func (c *Controller) cost() int64 {
  36. duration := c.End.UnixNano() - c.Start.UnixNano()
  37. return duration / 1e6
  38. }
  39. func (c *Controller) LogRequestBegin(r *http.Request) {
  40. info := fmt.Sprintf("requestId=%s\tevent=begin\turi=%s\taddress=%s\tbody=%s", c.RequestId, r.RequestURI, r.RemoteAddr, string(c.RequestBody))
  41. log.Info(info)
  42. }
  43. func (c *Controller) LogRequestEnd(r *http.Request) {
  44. info := fmt.Sprintf("requestId=%s\tevent=end\turi=%s\tcost=%d", c.RequestId, r.RequestURI, c.cost())
  45. log.Info(info)
  46. }
  47. func (c *Controller) SendError(w http.ResponseWriter, code int, msg string) {
  48. errInfo := fmt.Sprintf("requestId=%s\tbody=%s\terr=%s", c.RequestId, string(c.RequestBody), msg)
  49. log.Error(errInfo)
  50. e := ErrorResponse{
  51. Response: Response{
  52. Code: code,
  53. Message: msg,
  54. RequestId: c.RequestId,
  55. },
  56. }
  57. io.WriteString(w, e.ToString())
  58. }