常用类型及数据操作方法
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

105 lines
2.1 KiB

3 years ago
3 years ago
  1. package helper
  2. import (
  3. "encoding/json"
  4. "git.tetele.net/tgo/conf"
  5. "git.tetele.net/tgo/site"
  6. "git.tetele.net/tgo/userrpc"
  7. "io/ioutil"
  8. "log"
  9. "net/http"
  10. "strings"
  11. )
  12. type BaseController struct {
  13. W http.ResponseWriter
  14. Req *http.Request
  15. SiteInfo map[string]string
  16. UserInfo map[string]string
  17. Token string
  18. Domain string
  19. JsonData map[string]interface{}
  20. JsonDataArr []map[string]interface{}
  21. }
  22. //前置操作
  23. func (controller *BaseController)Construct(w http.ResponseWriter, req *http.Request) {
  24. log.Println("get from ", req.RemoteAddr, req.Method, req.Referer())
  25. controller.W = w
  26. controller.Req = req
  27. var replyJson []byte
  28. SetHeader(w, req)
  29. if strings.ToUpper(req.Method) == "OPTIONS" {
  30. replyJson, _ = json.Marshal(1)
  31. w.Write(replyJson)
  32. return
  33. }
  34. data := make(map[string]interface{})
  35. var err error
  36. if conf.IS_PRIVATE {
  37. controller.SiteInfo = map[string]string{
  38. "database": conf.DBNAME,
  39. "site_id": conf.SITE_ID,
  40. }
  41. } else {
  42. controller.SiteInfo, err = site.GetSiteInfoFromReq(conf.MASTER_URL, req)
  43. }
  44. if controller.Token != "" {
  45. controller.UserInfo, err = userrpc.GetUserByToken(controller.SiteInfo["database"], controller.Token, conf.USER_RPC_URL)
  46. }
  47. controller.Domain = GetDomain(req)
  48. //获取json数据
  49. body, _ := ioutil.ReadAll(req.Body)
  50. defer req.Body.Close()
  51. if len(body) > 0 {
  52. if strings.Index(string(body),"[{") == 0 {
  53. err = json.Unmarshal(body, &controller.JsonDataArr)
  54. } else{
  55. err = json.Unmarshal(body, &controller.JsonData)
  56. }
  57. }
  58. if err != nil {
  59. data["code"] = 0
  60. data["msg"] = err.Error()
  61. replyJson, _ = json.Marshal(data)
  62. w.Write(replyJson)
  63. return
  64. }
  65. }
  66. func (controller *BaseController) Success(result interface{}) {
  67. data := make(map[string]interface{})
  68. data["data"] = result
  69. data["code"] = 1
  70. data["msg"] = ""
  71. returnData, _ := json.Marshal(data)
  72. controller.W.Write(returnData)
  73. }
  74. func (controller *BaseController) Error(msg string) {
  75. data := make(map[string]interface{})
  76. data["data"] = nil
  77. data["code"] = 0
  78. data["msg"] = msg
  79. returnData, _ := json.Marshal(data)
  80. controller.W.Write(returnData)
  81. }