常用类型及数据操作方法
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.

106 lines
2.1 KiB

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