package app import ( "fmt" "net/http" "speech-nlu-parse/pkg/util" "time" "github.com/gin-gonic/gin" ) type Response struct { ctx *gin.Context } func NewResponse(ctx *gin.Context) *Response { response := &Response{ ctx: ctx, } response.ctx.Header("Content-Type", "application/json;charset=utf-8") return response } func (r *Response) ToResponse(v interface{}) { if r.ctx.Writer.Written() { return } data := v r.ctx.JSON(http.StatusOK, data) } func (r *Response) ToFormatErrResponse(errStr string) { fmt.Println(r.ctx.Writer.Written(), time.Now().Unix()) if r.ctx.Writer.Written() { return } data := gin.H{ "code": 401, "errorType": "request data error, check it and try again![" + errStr + "]", } r.ctx.JSON(http.StatusOK, data) } func (r *Response) ToByteResponse(data []byte) { if r.ctx.Writer.Written() { return } // 直接返回原始字节数据(确保data已经是合法的JSON字符串) //r.ctx.Data(http.StatusOK, "application/json", data) //r.ctx.JSON(http.StatusOK, data) //r.ctx.Data(http.StatusOK, "application/json;charset=utf-8", data) r.ctx.JSON(http.StatusOK, util.GetJsonTool().Get(data).GetInterface()) }