You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
paopao-ce/internal/servants/base/base.go

74 lines
1.4 KiB

// Copyright 2022 ROC. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package base
2 years ago
import (
"net/http"
"github.com/alimy/mir/v3"
2 years ago
"github.com/gin-gonic/gin"
"github.com/rocboss/paopao-ce/internal/core"
"github.com/rocboss/paopao-ce/pkg/xerror"
2 years ago
)
type BaseServant struct {
2 years ago
// TODO
}
type BaseBinding struct {
2 years ago
// TODO
}
type BaseRender struct {
2 years ago
// TODO
}
type JsonResp struct {
Code int `json:"code"`
Msg string `json:"msg,omitempty"`
Data any `json:",omitempty"`
}
type UserSetter interface {
SetUser(*core.User)
}
func UserFrom(c *gin.Context) (*core.User, bool) {
2 years ago
if u, exists := c.Get("USER"); exists {
user, ok := u.(*core.User)
2 years ago
return user, ok
}
return nil, false
}
func BindAny(c *gin.Context, obj any) mir.Error {
var errs xerror.ValidErrors
err := c.ShouldBind(obj)
if err != nil {
return mir.NewError(xerror.InvalidParams.Code(), xerror.InvalidParams.WithDetails(errs.Error()))
}
// setup *core.User if needed
if setter, ok := obj.(UserSetter); ok {
user, _ := UserFrom(c)
setter.SetUser(user)
}
return nil
}
func RenderAny(c *gin.Context, data any, err mir.Error) {
if err == nil {
c.JSON(http.StatusOK, &JsonResp{
Code: 0,
Msg: "success",
Data: data,
})
} else {
c.JSON(http.StatusInternalServerError, &JsonResp{
Code: err.StatusCode(),
Msg: err.Error(),
})
}
}