|
|
- package helper
-
- import (
- "encoding/json"
- "git.tetele.net/tgo/conf"
- "git.tetele.net/tgo/helper"
- "git.tetele.net/tgo/site"
- "git.tetele.net/tgo/userrpc"
- "io/ioutil"
- "log"
- "net/http"
- "strings"
- )
-
- type BaseController struct {
- W http.ResponseWriter
- Req *http.Request
- SiteInfo map[string]string
- UserInfo map[string]string
- Token string
- Domain string
- JsonData map[string]interface{}
- JsonDataArr []map[string]interface{}
- }
-
- //前置操作
- func (controller *BaseController)Construct(w http.ResponseWriter, req *http.Request) {
- log.Println("get from ", req.RemoteAddr, req.Method, req.Referer())
-
- controller.W = w
- controller.Req = req
-
- var replyJson []byte
-
- helper.SetHeader(w, req)
-
- if strings.ToUpper(req.Method) == "OPTIONS" {
- replyJson, _ = json.Marshal(1)
- w.Write(replyJson)
- return
- }
-
- data := make(map[string]interface{})
-
- var err error
-
- if conf.IS_PRIVATE {
- controller.SiteInfo = map[string]string{
- "database": conf.DBNAME,
- "site_id": conf.SITE_ID,
- }
- } else {
- controller.SiteInfo, err = site.GetSiteInfoFromReq(conf.MASTER_URL, req)
- }
-
- if controller.Token != "" {
- controller.UserInfo, err = userrpc.GetUserByToken(controller.SiteInfo["database"], controller.Token, conf.USER_RPC_URL)
- }
-
- controller.Domain = helper.GetDomain(req)
-
- //获取json数据
- body, _ := ioutil.ReadAll(req.Body)
- defer req.Body.Close()
-
- if len(body) > 0 {
- if strings.Index(string(body),"[{") == 0 {
- err = json.Unmarshal(body, &controller.JsonDataArr)
- } else{
- err = json.Unmarshal(body, &controller.JsonData)
- }
- }
-
- if err != nil {
- data["code"] = 0
- data["msg"] = err.Error()
- replyJson, _ = json.Marshal(data)
- w.Write(replyJson)
- return
- }
-
- }
-
- func (controller *BaseController) Success(result interface{}) {
- data := make(map[string]interface{})
-
- data["data"] = result
- data["code"] = 1
- data["msg"] = ""
-
- returnData, _ := json.Marshal(data)
-
- controller.W.Write(returnData)
- }
-
- func (controller *BaseController) Error(msg string) {
-
- data := make(map[string]interface{})
-
- data["data"] = nil
- data["code"] = 0
- data["msg"] = msg
-
- returnData, _ := json.Marshal(data)
-
- controller.W.Write(returnData)
- }
|