作者 yangfu

pkg更新

package contextdata
import (
"context"
)
func GetTenantFromCtx(ctx context.Context) int64 {
userToken := GetUserTokenFromCtx(ctx)
if userToken.CompanyId == 0 {
return 0
}
return userToken.CompanyId
}
... ... @@ -5,7 +5,6 @@ import (
"encoding/json"
"github.com/golang-jwt/jwt/v4"
"github.com/zeromicro/go-zero/core/logx"
"gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/pkg/config"
"time"
)
... ... @@ -63,22 +62,13 @@ type UserToken struct {
CompanyId int64 `json:"companyId"`
}
func (tk UserToken) GenerateToken(jwtConfig config.JwtAuth) (string, error) {
func (tk UserToken) GenerateToken(secret string, expire int64) (string, error) {
claims := make(jwt.MapClaims)
claims["exp"] = time.Now().Unix() + jwtConfig.Expire
claims["exp"] = time.Now().Unix() + expire
claims["iat"] = time.Now().Unix()
claims["UserId"] = tk.UserId
token := jwt.New(jwt.SigningMethodHS256)
token.Claims = claims
return token.SignedString([]byte(jwtConfig.AccessSecret))
}
func (tk *UserToken) ParseToken(jwtConfig config.JWT, str string) error {
return nil
}
// CheckUserInfo 如果UserToken有效 返回:true 否则返回false
func (tk *UserToken) CheckUserInfo() bool {
return !(tk.UserId > 100000000 || tk.UserId <= 0)
return token.SignedString([]byte(secret))
}
... ...
package result
import (
"fmt"
"gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/pkg/xerr"
"net/http"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/httpx"
"google.golang.org/grpc/status"
)
// http返回
func HttpResult(r *http.Request, w http.ResponseWriter, resp interface{}, err error) {
if err == nil {
//成功返回
r := Success(resp)
httpx.WriteJson(w, http.StatusOK, r)
} else {
//错误返回
errcode := xerr.SERVER_COMMON_ERROR
errmsg := "服务器开小差啦,稍后再来试一试"
internalErr := ""
causeErr := errors.Cause(err) // err类型
if e, ok := causeErr.(*xerr.CodeError); ok { //自定义错误类型
//自定义CodeError
errcode = e.GetErrCode()
errmsg = e.GetErrMsg()
if e.InternalError != nil {
internalErr = e.InternalError.Error()
}
} else {
if gstatus, ok := status.FromError(causeErr); ok { // grpc err错误
grpcCode := uint32(gstatus.Code())
if xerr.IsCodeErr(grpcCode) { //区分自定义错误跟系统底层、db等错误,底层、db错误不能返回给前端
errcode = grpcCode
errmsg = gstatus.Message()
}
}
}
logx.WithContext(r.Context()).Errorf("【API-ERR】 : %+v ", err)
response := Error(errcode, errmsg)
response.Error = internalErr
httpx.WriteJson(w, http.StatusOK, response)
}
}
// 授权的http方法
func AuthHttpResult(r *http.Request, w http.ResponseWriter, resp interface{}, err error) {
if err == nil {
//成功返回
r := Success(resp)
httpx.WriteJson(w, http.StatusOK, r)
} else {
//错误返回
errcode := xerr.SERVER_COMMON_ERROR
errmsg := "服务器开小差啦,稍后再来试一试"
causeErr := errors.Cause(err) // err类型
if e, ok := causeErr.(*xerr.CodeError); ok { //自定义错误类型
//自定义CodeError
errcode = e.GetErrCode()
errmsg = e.GetErrMsg()
} else {
if gstatus, ok := status.FromError(causeErr); ok { // grpc err错误
grpcCode := uint32(gstatus.Code())
if xerr.IsCodeErr(grpcCode) { //区分自定义错误跟系统底层、db等错误,底层、db错误不能返回给前端
errcode = grpcCode
errmsg = gstatus.Message()
}
}
}
logx.WithContext(r.Context()).Errorf("【GATEWAY-ERR】 : %+v ", err)
httpx.WriteJson(w, http.StatusUnauthorized, Error(errcode, errmsg))
}
}
// http 参数错误返回
func ParamErrorResult(r *http.Request, w http.ResponseWriter, err error) {
errMsg := fmt.Sprintf("%s ,%s", xerr.MapErrMsg(xerr.REUQEST_PARAM_ERROR), err.Error())
httpx.WriteJson(w, http.StatusBadRequest, Error(xerr.REUQEST_PARAM_ERROR, errMsg))
}
package result
import (
"fmt"
"gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/pkg/xerr"
"net/http"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/httpx"
"google.golang.org/grpc/status"
)
// HttpResult http响应结果返回
func HttpResult(r *http.Request, w http.ResponseWriter, resp interface{}, err error) {
// 成功返回
if err == nil {
r := Success(resp)
httpx.WriteJson(w, http.StatusOK, r)
return
}
//错误返回
errCode := xerr.ServerCommonError
errMsg := "服务器开小差啦,稍后再来试一试"
internalErr := ""
causeErr := errors.Cause(err)
codeError := &xerr.CodeError{}
if ok := errors.As(causeErr, codeError); ok { // 自定义错误类型
errCode = codeError.GetErrCode()
errMsg = codeError.GetErrMsg()
if codeError.InternalError != nil {
internalErr = codeError.InternalError.Error()
}
} else {
if grpcStatus, ok := status.FromError(causeErr); ok { // grpc err错误
grpcCode := uint32(grpcStatus.Code())
if xerr.IsCodeErr(grpcCode) {
errCode = grpcCode
errMsg = grpcStatus.Message()
}
}
}
// TODO:区分自定义错误跟系统底层、db等错误,底层、db错误不能返回给前端
logx.WithContext(r.Context()).Errorf("【API-ERR】 : %+v ", err)
response := Error(errCode, errMsg)
response.Error = internalErr
httpx.WriteJson(w, http.StatusOK, response)
}
// ParamErrorResult http参数错误返回
func ParamErrorResult(r *http.Request, w http.ResponseWriter, err error) {
errMsg := fmt.Sprintf("%s ,%s", xerr.MapErrMsg(xerr.RequestParamError), err.Error())
httpx.WriteJson(w, http.StatusBadRequest, Error(xerr.RequestParamError, errMsg))
}
... ...
package result
import (
"context"
"gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/pkg/xerr"
"github.com/pkg/errors"
"github.com/zeromicro/go-zero/core/logx"
"google.golang.org/grpc/status"
)
// job返回
func JobResult(ctx context.Context, resp interface{}, err error) {
if err == nil {
// 成功返回 ,只有dev环境下才会打印info,线上不显示
if resp != nil {
logx.Infof("resp: %+v", resp)
}
return
} else {
errCode := xerr.SERVER_COMMON_ERROR
errMsg := "服务器开小差啦,稍后再来试一试"
// 错误返回
causeErr := errors.Cause(err) // err类型
if e, ok := causeErr.(*xerr.CodeError); ok { // 自定义错误类型
// 自定义CodeError
errCode = e.GetErrCode()
errMsg = e.GetErrMsg()
} else {
if gstatus, ok := status.FromError(causeErr); ok { // grpc err错误
grpcCode := uint32(gstatus.Code())
if xerr.IsCodeErr(grpcCode) { // 区分自定义错误跟系统底层、db等错误,底层、db错误不能返回给前端
errCode = grpcCode
errMsg = gstatus.Message()
}
}
}
logx.WithContext(ctx).Errorf("【JOB-ERR】 : %+v ,errCode:%d , errMsg:%s ", err, errCode, errMsg)
return
}
}
package xerr
/**默认的服务错误**/
func NewErr(err error) *CodeError {
return &CodeError{errCode: ServerCommonError, InternalError: err}
}
func NewErrMsg(errMsg string) *CodeError {
return &CodeError{errCode: ServerCommonError, errMsg: errMsg}
}
func NewErrMsgErr(errMsg string, internalError error) *CodeError {
return &CodeError{errCode: ServerCommonError, errMsg: errMsg, InternalError: internalError}
}
/**指定错误码的错误**/
func NewCodeErr(errCode uint32, err error) *CodeError {
return &CodeError{errCode: errCode, errMsg: MapErrMsg(errCode), InternalError: err}
}
func NewCodeErrMsg(errCode uint32, err error, msg string) *CodeError {
return &CodeError{errCode: errCode, errMsg: msg, InternalError: err}
}
... ...
package xerr
// 成功返回
const OK uint32 = 200
/**(前3位代表业务,后三位代表具体功能)**/
// 全局错误码
const SERVER_COMMON_ERROR uint32 = 100001
const REUQEST_PARAM_ERROR uint32 = 100002
const TOKEN_EXPIRE_ERROR uint32 = 100003
const TOKEN_GENERATE_ERROR uint32 = 100004
const DB_ERROR uint32 = 100005
const DB_UPDATE_AFFECTED_ZERO_ERROR uint32 = 100006
const REQUEST_ARGS_ERROR = 200001
// 微信模块
const ErrWxMiniAuthFailError uint32 = 500001
const ErrUserNoAuth uint32 = 500002
package xerr
import (
"fmt"
import "fmt"
const (
// OK 成功返回
OK uint32 = 200
)
// 全局错误码
// 系统错误前3位代表业务,后三位代表具体功能
const (
ServerCommonError uint32 = 100001 // 系统错误
RequestParamError uint32 = 100002 // 参数请求错误
TokenExpireError uint32 = 100003 // token失效
TokenGenerateError uint32 = 100004 // 生成token失败
DbError uint32 = 100005 // 数据库错误
DbUpdateAffectedZeroError uint32 = 100006 // 数据库更新错误
)
/**
常用通用固定错误
*/
/**微信模块**/
const (
ErrWxMiniAuthFailError uint32 = 500001
ErrUserNoAuth uint32 = 500002
)
type CodeError struct {
errCode uint32
... ... @@ -33,31 +49,3 @@ func (e *CodeError) Error() string {
}
return fmt.Sprintf("ErrCode:%d,ErrMsg:%s", e.errCode, e.errMsg)
}
/*
指定错误码的错误
*/
func NewCodeErr(errCode uint32, err error) *CodeError {
return &CodeError{errCode: errCode, errMsg: MapErrMsg(errCode), InternalError: err}
}
func NewCodeErrMsg(errCode uint32, err error, msg string) *CodeError {
return &CodeError{errCode: errCode, errMsg: msg, InternalError: err}
}
/*
默认的服务错误
*/
func NewErr(err error) *CodeError {
return &CodeError{errCode: SERVER_COMMON_ERROR, InternalError: err}
}
func NewErrMsg(errMsg string) *CodeError {
return &CodeError{errCode: SERVER_COMMON_ERROR, errMsg: errMsg}
}
func NewErrMsgErr(errMsg string, err error) *CodeError {
return &CodeError{errCode: SERVER_COMMON_ERROR, errMsg: errMsg, InternalError: err}
}
... ...
... ... @@ -5,26 +5,26 @@ var message map[uint32]string
func init() {
message = make(map[uint32]string)
message[OK] = "SUCCESS"
message[SERVER_COMMON_ERROR] = "服务器开小差啦,稍后再来试一试"
message[REUQEST_PARAM_ERROR] = "参数错误"
message[TOKEN_EXPIRE_ERROR] = "token失效,请重新登陆"
message[TOKEN_GENERATE_ERROR] = "生成token失败"
message[DB_ERROR] = "数据库繁忙,请稍后再试"
message[DB_UPDATE_AFFECTED_ZERO_ERROR] = "更新数据影响行数为0"
message[ServerCommonError] = "服务器开小差啦,稍后再来试一试"
message[RequestParamError] = "参数错误"
message[TokenExpireError] = "token失效,请重新登陆"
message[TokenGenerateError] = "生成token失败"
message[DbError] = "数据库繁忙,请稍后再试"
message[DbUpdateAffectedZeroError] = "更新数据影响行数为0"
message[ErrUserNoAuth] = "无权限"
message[ErrWxMiniAuthFailError] = "微信授权失败"
}
func MapErrMsg(errcode uint32) string {
if msg, ok := message[errcode]; ok {
func MapErrMsg(errCode uint32) string {
if msg, ok := message[errCode]; ok {
return msg
} else {
return "服务器开小差啦,稍后再来试一试"
}
}
func IsCodeErr(errcode uint32) bool {
if _, ok := message[errcode]; ok {
func IsCodeErr(errCode uint32) bool {
if _, ok := message[errCode]; ok {
return true
} else {
return false
... ...