package router import ( "encoding/json" "github.com/gin-gonic/gin" "github.com/google/uuid" "github.com/tidwall/gjson" "net/http" "speech-nlu-parse/app" "speech-nlu-parse/global" "speech-nlu-parse/model" "speech-nlu-parse/pkg/logger" "speech-nlu-parse/pkg/proto" "speech-nlu-parse/service/speechNlu" "strings" ) func InitRouter() (engine *gin.Engine) { // 获取并增加日志与恢复中间件 //engine = gin.Default() engine = gin.New() engine.Use(gin.Recovery()) // 校验AppKey engine.Use(VerifyAppKeyMiddleware()) // 超时限制测试 //engine.Use(middleware.TimeLimitMiddleware(time.Second * 5)) engine.POST(global.ServerSetting.UriPath, Controller) return } type SnpReq struct { Ip string `json:"ip"` Mac string `json:"mac"` Mid string `json:"mid"` Query string `json:"query"` RequestId string `json:"requestId"` } func Controller(ctx *gin.Context) { req := SnpReq{} response := app.NewResponse(ctx) if err := ctx.ShouldBind(&req); err != nil { global.Logger.Errorf("redis.ShouldBind err: %v ", err) response.ToFormatErrResponse(err.Error()) return } if strings.TrimSpace(req.Query) == "" || strings.TrimSpace(req.Mac) == "" { response.ToFormatErrResponse("请求格式错误") return } if req.Ip == "" { req.Ip = ctx.ClientIP() } if req.RequestId == "" { req.RequestId = uuid.New().String() } global.Logger.WithFields(logger.Fields{"query": req.Query, "mac": req.Mac, "mid": req.Mid, "requestId": req.RequestId, "ip": req.Ip}).Info("speech-nlu-parse-http request") semanticReq := SpeechNluParseSemanticRequest(req) jsonStr, code := speechNlu.SpeechNlu(semanticReq) responseText := gjson.Get(jsonStr, "response_text").String() response1 := &proto.SemanticResponse{Status: &proto.Status{Code: code.Code(), Msg: code.Msg()}, Data: &proto.SemanticData{SemanticRespJsonData: jsonStr}} responseBody, _ := json.Marshal(response1) defer global.Logger.WithFields(logger.Fields{"data": map[string]interface{}{"responseBody": string(responseBody), "query": req.Query, "responseText": responseText}, "mac": req.Mac, "mid": req.Mid, "requestId": req.RequestId, "ip": req.Ip}).Info("speech-nlu-parse-http response") // 直接返回 semanticRespJsonData 的原始内容(已经是JSON字符串) //ctx.Data(http.StatusOK, "application/json", []byte(jsonStr)) response.ToByteResponse([]byte(jsonStr)) return } func SpeechNluParseSemanticRequest(req SnpReq) *model.SemanticReq { semanticReq := &model.SemanticReq{ MacWifi: req.Mac, MacVoice: req.Mac, Query: req.Query, Ip: req.Ip, OriginQuery: req.Query, Mid: req.Mid, RequestId: req.RequestId, } return semanticReq } // 校验AppKey func VerifyAppKeyMiddleware() gin.HandlerFunc { validAppKeys := map[string]bool{ global.ServerSetting.AppKey: true, } return func(c *gin.Context) { appKey := c.GetHeader("X-AppKey") if appKey == "" { c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{ "error": "App key is required", }) return } if !validAppKeys[appKey] { c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{ "error": "Invalid app key", }) return } c.Next() } }