package controllers
import (
"encoding/json"
"eta/eta_crawler/models"
"eta/eta_crawler/utils"
"fmt"
"github.com/beego/beego/v2/server/web"
"github.com/shopspring/decimal"
"net/http"
"net/url"
"reflect"
)
type BaseAuthController struct {
web.Controller
}
func (this *BaseAuthController) Prepare() {
fmt.Println("enter prepare")
method := this.Ctx.Input.Method()
uri := this.Ctx.Input.URI()
fmt.Println("Url:", uri)
if method != "HEAD" {
//if method == "POST" {
// ok, errMsg := checkSign(this)
// if !ok {
// this.JSON(models.BaseResponse{Ret: 408, Msg: "签名错误!", ErrMsg: errMsg}, false, false)
// this.StopRun()
// return
// }
//} else {
// this.JSON(models.BaseResponse{Ret: 408, Msg: "请求异常,请联系客服!", ErrMsg: "POST之外的请求,暂不支持"}, false, false)
// this.StopRun()
// return
//}
} else {
this.JSON(models.BaseResponse{Ret: 408, Msg: "请求异常,请联系客服!", ErrMsg: "method:" + method}, false, false)
this.StopRun()
return
}
}
//func checkSign(c *BaseAuthController) (ok bool, errMsg string) {
// method := c.Ctx.Input.Method()
// signData := make(map[string]string)
//
// switch method {
// case "GET":
// //requestBody = c.Ctx.Request.RequestURI
// params := c.Ctx.Request.URL.Query()
// signData = convertParam(params)
// case "POST":
// //requestBody, _ = url.QueryUnescape(string(c.Ctx.Input.RequestBody))
//
// //请求类型
// contentType := c.Ctx.Request.Header.Get("content-type")
// //fmt.Println("contentType:", contentType)
// //fmt.Println("c.Ctx.Input.RequestBody:", string(c.Ctx.Input.RequestBody))
//
// switch contentType {
// case "multipart/form-data":
// //文件最大5M
// err := c.Ctx.Request.ParseMultipartForm(-int64(5 << 20))
// if err != nil {
// errMsg = fmt.Sprintf("获取参数失败,%v", err)
// return
// }
// params := c.Ctx.Request.Form
// signData = convertParam(params)
// case "application/x-www-form-urlencoded":
// err := c.Ctx.Request.ParseForm()
// if err != nil {
// errMsg = fmt.Sprintf("获取参数失败,%v", err)
// return
// }
// params := c.Ctx.Request.Form
// signData = convertParam(params)
// case "application/json":
// //var v interface{}
// params := make(map[string]interface{})
// err := json.Unmarshal(c.Ctx.Input.RequestBody, ¶ms)
// if err != nil {
// errMsg = fmt.Sprintf("获取参数失败,%v", err)
// return
// }
// //fmt.Println("params:", params)
//
// signData = convertParamInterface(params)
// //tmpV := v.(map[string]string)
// //fmt.Println("tmpV:", tmpV)
// //fmt.Sprintln("list type is v%", tmpV["list"])
// default: //正常应该是其他方式获取解析的,暂时这么处理吧
// err := c.Ctx.Request.ParseForm()
// if err != nil {
// errMsg = fmt.Sprintf("获取参数失败,%v", err)
// return
// }
// params := c.Ctx.Request.Form
// signData = convertParam(params)
// }
// }
//
// // 开始校验数据
// ip := c.Ctx.Input.IP()
// err := checkSignData(signData, ip)
// if err != nil {
// errMsg = fmt.Sprintf("签名校验失败,%v", err)
// return
// }
//
// ok = true
// return
//}
func (c *BaseAuthController) ServeJSON(encoding ...bool) {
// 方法处理完后,需要后置处理的业务逻辑
//if handlerList, ok := AfterHandlerUrlMap[c.Ctx.Request.URL.Path]; ok {
// for _, handler := range handlerList {
// handler(c.Ctx.Input.RequestBody)
// }
//}
//所有请求都做这么个处理吧,目前这边都是做编辑、刷新逻辑处理(新增的话,并没有指标id,不会有影响)
var (
hasIndent = false
hasEncoding = false
)
if web.BConfig.RunMode == web.PROD {
hasIndent = false
}
if len(encoding) > 0 && encoding[0] == true {
hasEncoding = true
}
if c.Data["json"] == nil {
go utils.SendEmail("异常提醒:", "接口:"+"URI:"+c.Ctx.Input.URI()+";无返回值", utils.EmailSendToUsers)
return
}
baseRes := c.Data["json"].(*models.BaseResponse)
if baseRes != nil && baseRes.Ret != 408 {
//body, _ := json.Marshal(baseRes)
//var requestBody string
//method := c.Ctx.Input.Method()
//if method == "GET" {
// requestBody = c.Ctx.Request.RequestURI
//} else {
// requestBody, _ = url.QueryUnescape(string(c.Ctx.Input.RequestBody))
//}
//if baseRes.Ret != 200 && baseRes.IsSendEmail {
// go utils.SendEmail(utils.APP_NAME_CN+"【"+utils.RunMode+"】"+"失败提醒", "URI:"+c.Ctx.Input.URI()+"
"+"Params"+requestBody+"
"+"ErrMsg:"+baseRes.ErrMsg+";
Msg:"+baseRes.Msg+";
Body:"+string(body)+"
", utils.EmailSendToUsers)
//}
}
c.JSON(c.Data["json"], hasIndent, hasEncoding)
}
func (c *BaseAuthController) JSON(data interface{}, hasIndent bool, coding bool) error {
c.Ctx.Output.Header("Content-Type", "application/json; charset=utf-8")
var content []byte
var err error
if hasIndent {
content, err = json.MarshalIndent(data, "", " ")
} else {
content, err = json.Marshal(data)
}
if err != nil {
http.Error(c.Ctx.Output.Context.ResponseWriter, err.Error(), http.StatusInternalServerError)
return err
}
ip := c.Ctx.Input.IP()
requestBody, err := url.QueryUnescape(string(c.Ctx.Input.RequestBody))
if err != nil {
requestBody = string(c.Ctx.Input.RequestBody)
}
if requestBody == "" {
requestBody = c.Ctx.Input.URI()
}
c.logUri(content, requestBody, ip)
if coding {
content = []byte(utils.StringsToJSON(string(content)))
}
return c.Ctx.Output.Body(content)
}
// 将请求传入的数据格式转换成签名需要的格式
func convertParam(params map[string][]string) (signData map[string]string) {
signData = make(map[string]string)
for key := range params {
signData[key] = params[key][0]
}
return signData
}
// 将请求传入的数据格式转换成签名需要的格式(目前只能处理简单的类型,数组、对象暂不支持)
func convertParamInterface(params map[string]interface{}) (signData map[string]string) {
signData = make(map[string]string)
for key := range params {
val := ``
//fmt.Println("key", key, ";val:", params[key], ";type:", reflect.TypeOf(params[key]))
//signData[key] = params[key][0]
tmpVal := params[key]
switch reflect.TypeOf(tmpVal).Kind() {
case reflect.String:
val = fmt.Sprint(tmpVal)
case reflect.Int, reflect.Int16, reflect.Int64, reflect.Int32, reflect.Int8:
val = fmt.Sprint(tmpVal)
case reflect.Uint, reflect.Uint32, reflect.Uint16, reflect.Uint8, reflect.Uint64:
val = fmt.Sprint(tmpVal)
case reflect.Bool:
val = fmt.Sprint(tmpVal)
case reflect.Float64:
decimalNum := decimal.NewFromFloat(tmpVal.(float64))
val = decimalNum.String()
//val = strconv.FormatFloat(tmpVal.(float64), 'E', -1, 64) //float64
case reflect.Float32:
decimalNum := decimal.NewFromFloat32(tmpVal.(float32))
val = decimalNum.String()
}
signData[key] = val
}
return signData
}
func (c *BaseAuthController) logUri(content []byte, requestBody, ip string) {
utils.ApiLog.Info("uri:%s, requestBody:%s, responseBody:%s, ip:%s", c.Ctx.Input.URI(), requestBody, content, ip)
return
}