package response import ( "fmt" "lone-services/pkg/utils" "net/http" "net/url" jsoniter "github.com/json-iterator/go" ) var jsonAPI = jsoniter.Config{EscapeHTML: false}.Froze() type BaseController struct{} func (b *BaseController) Fail(w http.ResponseWriter) { b.Out(w, nil, Fail) } func (b *BaseController) Error(w http.ResponseWriter, cm Error) { b.Out(w, nil, cm) } func (b *BaseController) Out(w http.ResponseWriter, data any, cm Error) { out := NewError(cm.GetCode(), cm.GetMsg()).WithData(data) w.Header().Set("Content-Type", "application/json; charset=utf-8") w.WriteHeader(http.StatusOK) _ = jsonAPI.NewEncoder(w).Encode(out) } func (b *BaseController) OutPut(w http.ResponseWriter, code int32, data any, msg string) { if code == utils.Ok.Code && !utils.GetConfigBool("encrypt.debug") { jsonData, err := jsonAPI.Marshal(data) if err != nil { fmt.Printf("response encrypt: json.Marshal failed: %v\n", err) msg = utils.ErrorEncryptAesError.Msg code = utils.ErrorEncryptAesError.Code } else { key := utils.GetConfigString("encrypt.encrypt_key") res, enErr := utils.Crypto{}.Encrypt(jsonData) if enErr != nil { fmt.Printf("response encrypt failed: keyLen=%d keyEmpty=%v errCode=%d errMsg=%s\n", len(key), key == "", enErr.GetCode(), enErr.GetMsg()) msg = utils.ErrorEncryptAesError.Msg code = utils.ErrorEncryptAesError.Code } else { data = res } } } out := NewError(int(code), msg).WithData(data) w.Header().Set("Content-Type", "application/json; charset=utf-8") w.WriteHeader(http.StatusOK) _ = jsonAPI.NewEncoder(w).Encode(out) } func (b *BaseController) OutPutBack(w http.ResponseWriter, back responseDataBack) { w.Header().Set("Content-Type", "application/json; charset=utf-8") w.WriteHeader(http.StatusOK) _ = jsonAPI.NewEncoder(w).Encode(back) } func (b *BaseController) OutPutDown(w http.ResponseWriter, back responseDataDown) { // 下载头,二进制流 w.Header().Set("Content-Type", "application/octet-stream") // 文件名 urlencode,防止中文乱码 w.Header().Set("Content-Disposition", `attachment; filename="`+url.QueryEscape(back.Name)+`"`) w.Header().Set("Content-Transfer-Encoding", "binary") w.WriteHeader(http.StatusOK) // back.Data 是 []byte excel二进制 _, _ = w.Write([]byte(back.Data)) }