Browse Source

加入辅助方法

master
listen 3 years ago
parent
commit
3abc42ee24
2 changed files with 137 additions and 0 deletions
  1. +107
    -0
      base.go
  2. +30
    -0
      map.go

+ 107
- 0
base.go View File

@ -0,0 +1,107 @@
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)
}

+ 30
- 0
map.go View File

@ -61,3 +61,33 @@ func ToMapStringArray(x interface{}) ([]map[string]string, error) {
return ret, err
}
/**
* 将map[string]string数组转成map[string]interface数组
*/
func MapStringToInterfaceArr(src []map[string]string)([]map[string]interface{}){
var dest []map[string]interface{}
for i := range src {
m := src[i]
n := make(map[string]interface{})
for k,v := range m {
n[k] = interface{}(v)
}
dest = append(dest, n)
}
return dest
}
/**
* 将map[string]string转成map[string]interface
*/
func MapStringToInterface(src map[string]string)(map[string]interface{}){
target := make(map[string]interface{})
for k,v := range src {
target[k] = interface{}(v)
}
return target
}

Loading…
Cancel
Save