message.go 938 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package response
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. )
  6. type Response struct {
  7. Code int `json:"code"`
  8. Message string `json:"message"`
  9. Data interface{} `json:"data"`
  10. }
  11. var response = Response{
  12. Code: 200,
  13. Message: "",
  14. Data: nil,
  15. }
  16. type PageResponse struct {
  17. PageSize int `json:"pageSize"`
  18. Page int `json:"page"`
  19. HNext bool `json:"HNext"`
  20. Data interface{} `json:"data"`
  21. }
  22. func Success(w http.ResponseWriter, message string, data interface{}) {
  23. w.Header().Set("Content-Type", "application/json")
  24. w.WriteHeader(http.StatusOK)
  25. rsp := response
  26. rsp.Message = message
  27. rsp.Data = data
  28. r, _ := json.Marshal(rsp)
  29. w.Write(r)
  30. }
  31. func Fail(w http.ResponseWriter, message string, code int) {
  32. w.Header().Set("Content-Type", "application/json")
  33. w.WriteHeader(http.StatusOK)
  34. rsp := response
  35. rsp.Code = code
  36. rsp.Message = message
  37. r, _ := json.Marshal(rsp)
  38. w.Write(r)
  39. }