61 lines
1.7 KiB
Go
61 lines
1.7 KiB
Go
package response
|
|
|
|
import (
|
|
"fmt"
|
|
"lone-services/pkg/utils"
|
|
"net/http"
|
|
|
|
jsoniter "github.com/json-iterator/go"
|
|
)
|
|
|
|
type BaseController struct{}
|
|
|
|
// Fail 基础错误的输出结果
|
|
func (b *BaseController) Fail(w http.ResponseWriter) {
|
|
b.Out(w, nil, Fail)
|
|
}
|
|
|
|
// Error 错误的输出结果
|
|
func (b *BaseController) Error(w http.ResponseWriter, cm Error) {
|
|
b.Out(w, nil, cm)
|
|
}
|
|
|
|
// Out 输出结果
|
|
func (b *BaseController) Out(w http.ResponseWriter, data any, cm Error) {
|
|
// 复制一份,避免并发请求改到包级 OK/Fail 单例
|
|
out := NewError(cm.GetCode(), cm.GetMsg()).WithData(data)
|
|
|
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
|
w.WriteHeader(http.StatusOK)
|
|
_ = jsoniter.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 := jsoniter.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
|
|
}
|
|
}
|
|
}
|
|
|
|
// 复制一份,避免并发请求改到包级 OK/Fail 单例
|
|
out := NewError(int(code), msg).WithData(data)
|
|
|
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
|
w.WriteHeader(http.StatusOK)
|
|
_ = jsoniter.NewEncoder(w).Encode(out)
|
|
}
|