context.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package context
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "strings"
  6. )
  7. type Result struct {
  8. Code int `json:"code,omitempty"`
  9. Lang string `json:"lang,omitempty"`
  10. Message string `json:"message,omitempty"`
  11. T string `json:"t,omitempty"`
  12. R string `json:"r,omitempty"`
  13. Topic string `json:"topic,omitempty"`
  14. }
  15. type Result_b struct {
  16. Code int `json:"code,omitempty"`
  17. Lang string `json:"lang,omitempty"`
  18. Message string `json:"message,omitempty"`
  19. T string `json:"t,omitempty"`
  20. R string `json:"r,omitempty"`
  21. Topic string `json:"topic,omitempty"`
  22. }
  23. type Context struct {
  24. Writer http.ResponseWriter
  25. Req *http.Request
  26. }
  27. func (c *Context) IsGet() bool {
  28. return c.Method() == http.MethodGet
  29. }
  30. func (c *Context) IsPost() bool {
  31. return c.Method() == http.MethodPost
  32. }
  33. func (c *Context) Method() string {
  34. return strings.ToUpper(c.Req.Method)
  35. }
  36. func (c *Context) NotAllow() {
  37. c.Writer.WriteHeader(http.StatusMethodNotAllowed)
  38. }
  39. func (c *Context) JSON(code int, data interface{}) error {
  40. c.Writer.Header().Add("Content-Type", "application/json")
  41. content, _ := json.Marshal(data)
  42. c.res(code, content)
  43. return nil
  44. }
  45. func (c *Context) RunOK(lang, message, T, R, Topic string) {
  46. _ = c.JSON(http.StatusOK, &Result{200, lang, message, T, R, Topic})
  47. }
  48. func (c *Context) Bad(message string) {
  49. c.RunRet(http.StatusBadRequest, message)
  50. }
  51. func (c *Context) Error(message string) {
  52. c.RunRet(http.StatusInternalServerError, message)
  53. }
  54. func (c *Context) Timeout(message string) {
  55. c.RunRet(http.StatusRequestTimeout, message)
  56. }
  57. func (c *Context) RunRet(code int, message string) {
  58. _ = c.JSON(200, &Result{code, "", message, "", "", ""})
  59. }
  60. func (c *Context) res(code int, data []byte) {
  61. c.Writer.WriteHeader(code)
  62. _, _ = c.Writer.Write(data)
  63. }
  64. func (c *Context) Get(key string, def string) string {
  65. val := c.Req.URL.Query().Get(key)
  66. if val == "" {
  67. return def
  68. }
  69. return val
  70. }