add a helper function (#443)

This commit is contained in:
UUBulb 2024-10-21 12:11:02 +08:00 committed by GitHub
parent aa20c97312
commit cf5408751e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 21 additions and 6 deletions

View File

@ -2,15 +2,16 @@ package controller
import (
"encoding/json"
"fmt"
"net/http"
"time"
jwt "github.com/appleboy/gin-jwt/v2"
"github.com/gin-gonic/gin"
"github.com/naiba/nezha/model"
"github.com/naiba/nezha/service/singleton"
"golang.org/x/crypto/bcrypt"
"github.com/naiba/nezha/model"
"github.com/naiba/nezha/pkg/utils"
"github.com/naiba/nezha/service/singleton"
)
func initParams() *jwt.GinJWTMiddleware {
@ -96,7 +97,7 @@ func authenticator() func(c *gin.Context) (interface{}, error) {
return nil, jwt.ErrFailedAuthentication
}
return fmt.Sprintf("%d", user.ID), nil
return utils.Itoa(user.ID), nil
}
}

View File

@ -27,7 +27,7 @@ func listServerGroup(c *gin.Context) {
c.JSON(http.StatusOK, model.CommonResponse[[]model.ServerGroup]{
Success: err == nil,
Data: sg,
Error: utils.IfOrFn[string](err == nil, func() string {
Error: utils.IfOrFn(err == nil, func() string {
return err.Error()
}, func() string {
return ""

2
go.mod
View File

@ -28,6 +28,7 @@ require (
github.com/swaggo/swag v1.16.4
github.com/tidwall/gjson v1.18.0
golang.org/x/crypto v0.26.0
golang.org/x/exp v0.0.0-20230905200255-921286631fa9
golang.org/x/net v0.28.0
golang.org/x/sync v0.8.0
google.golang.org/grpc v1.63.0
@ -86,7 +87,6 @@ require (
go.uber.org/atomic v1.9.0 // indirect
go.uber.org/multierr v1.9.0 // indirect
golang.org/x/arch v0.9.0 // indirect
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 // indirect
golang.org/x/mod v0.18.0 // indirect
golang.org/x/sys v0.24.0 // indirect
golang.org/x/text v0.17.0 // indirect

View File

@ -5,8 +5,11 @@ import (
"math/big"
"os"
"regexp"
"strconv"
"strings"
"golang.org/x/exp/constraints"
jsoniter "github.com/json-iterator/go"
)
@ -104,3 +107,14 @@ func IfOrFn[T any](a bool, x, y func() T) T {
}
return y()
}
func Itoa[T constraints.Integer](i T) string {
switch any(i).(type) {
case int, int8, int16, int32, int64:
return strconv.FormatInt(int64(i), 10)
case uint, uint8, uint16, uint32, uint64:
return strconv.FormatUint(uint64(i), 10)
default:
return ""
}
}