u
This commit is contained in:
1 parent
500fab7a80
commit
8f3f6982db
54 files changed
+2076
-1877
No files matched your search
@@ -0,0 +1,165 @@
|
||||
package httpx
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/cloudwego/hertz/pkg/app/client"
|
||||
"github.com/cloudwego/hertz/pkg/protocol"
|
||||
"github.com/cloudwego/hertz/pkg/protocol/consts"
|
||||
)
|
||||
|
||||
var (
|
||||
once sync.Once
|
||||
clientInstance *HertzClient
|
||||
)
|
||||
|
||||
// HertzClient 定义
|
||||
type HertzClient struct {
|
||||
Client *client.Client
|
||||
Timeout time.Duration
|
||||
Header map[string]string
|
||||
}
|
||||
|
||||
// Init 初始化单例
|
||||
func Init() {
|
||||
once.Do(func() {
|
||||
c, _ := client.NewClient()
|
||||
clientInstance = &HertzClient{
|
||||
Client: c,
|
||||
Timeout: 5 * time.Second,
|
||||
Header: make(map[string]string),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// SetHeader 设置默认 header
|
||||
func SetHeader(key, value string) {
|
||||
if clientInstance == nil {
|
||||
Init()
|
||||
}
|
||||
clientInstance.Header[key] = value
|
||||
}
|
||||
|
||||
// 支持 value 为任意类型
|
||||
func buildQueryString(query map[string][]any) string {
|
||||
if len(query) == 0 {
|
||||
return ""
|
||||
}
|
||||
|
||||
values := url.Values{}
|
||||
for k, arr := range query {
|
||||
for _, v := range arr {
|
||||
values.Add(k, fmt.Sprintf("%v", v)) // 自动转 string
|
||||
}
|
||||
}
|
||||
return values.Encode()
|
||||
}
|
||||
|
||||
func Get(ctx context.Context, urlStr string, query map[string][]any) (int, string, error) {
|
||||
if clientInstance == nil {
|
||||
Init()
|
||||
}
|
||||
h := clientInstance
|
||||
req := &protocol.Request{}
|
||||
res := &protocol.Response{}
|
||||
|
||||
req.Header.SetMethod(consts.MethodGet)
|
||||
req.SetRequestURI(urlStr)
|
||||
if qs := buildQueryString(query); qs != "" {
|
||||
req.SetQueryString(qs)
|
||||
}
|
||||
|
||||
for k, v := range h.Header {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(ctx, h.Timeout)
|
||||
defer cancel()
|
||||
|
||||
err := h.Client.Do(ctx, req, res)
|
||||
if err != nil {
|
||||
return 0, "", err
|
||||
}
|
||||
|
||||
return res.StatusCode(), string(res.Body()), nil
|
||||
}
|
||||
|
||||
func PostJSON(ctx context.Context, urlStr string, query map[string][]any, payload any) (int, string, error) {
|
||||
if clientInstance == nil {
|
||||
Init()
|
||||
}
|
||||
h := clientInstance
|
||||
req := &protocol.Request{}
|
||||
res := &protocol.Response{}
|
||||
|
||||
req.Header.SetMethod(consts.MethodPost)
|
||||
req.Header.SetContentTypeBytes([]byte("application/json"))
|
||||
req.SetRequestURI(urlStr)
|
||||
if qs := buildQueryString(query); qs != "" {
|
||||
req.SetQueryString(qs)
|
||||
}
|
||||
|
||||
data, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return 0, "", fmt.Errorf("marshal json error: %w", err)
|
||||
}
|
||||
req.SetBody(data)
|
||||
|
||||
for k, v := range h.Header {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(ctx, h.Timeout)
|
||||
defer cancel()
|
||||
|
||||
err = h.Client.Do(ctx, req, res)
|
||||
if err != nil {
|
||||
return 0, "", err
|
||||
}
|
||||
|
||||
return res.StatusCode(), string(res.Body()), nil
|
||||
}
|
||||
|
||||
func PostForm(ctx context.Context, urlStr string, query map[string][]any, form map[string]string) (int, string, error) {
|
||||
if clientInstance == nil {
|
||||
Init()
|
||||
}
|
||||
h := clientInstance
|
||||
req := &protocol.Request{}
|
||||
res := &protocol.Response{}
|
||||
|
||||
req.Header.SetMethod(consts.MethodPost)
|
||||
req.SetRequestURI(urlStr)
|
||||
if qs := buildQueryString(query); qs != "" {
|
||||
req.SetQueryString(qs)
|
||||
}
|
||||
|
||||
req.SetFormData(form)
|
||||
|
||||
for k, v := range h.Header {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(ctx, h.Timeout)
|
||||
defer cancel()
|
||||
|
||||
err := h.Client.Do(ctx, req, res)
|
||||
if err != nil {
|
||||
return 0, "", err
|
||||
}
|
||||
|
||||
return res.StatusCode(), string(res.Body()), nil
|
||||
}
|
||||
|
||||
func JSONStringToMap(jsonStr string) (map[string]interface{}, error) {
|
||||
var result map[string]interface{}
|
||||
if err := json.Unmarshal([]byte(jsonStr), &result); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
@@ -6,17 +6,22 @@ import (
|
||||
)
|
||||
|
||||
// GenerateCode 生成指定长度的随机邀请码(大写字母+数字)
|
||||
func GenerateCode(length int) (string, error) {
|
||||
// 不会返回错误,如果随机失败,会自动重试
|
||||
func GenerateCode(length int) string {
|
||||
const charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
||||
code := make([]byte, length)
|
||||
|
||||
for i := 0; i < length; i++ {
|
||||
num, err := rand.Int(rand.Reader, big.NewInt(int64(len(charset))))
|
||||
if err != nil {
|
||||
return "", err
|
||||
for {
|
||||
num, err := rand.Int(rand.Reader, big.NewInt(int64(len(charset))))
|
||||
if err != nil {
|
||||
// 随机失败,重试
|
||||
continue
|
||||
}
|
||||
code[i] = charset[num.Int64()]
|
||||
break
|
||||
}
|
||||
code[i] = charset[num.Int64()]
|
||||
}
|
||||
|
||||
return string(code), nil
|
||||
return string(code)
|
||||
}
|
||||
@@ -13,16 +13,9 @@ type CustomClaims struct {
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
type TokenResult struct {
|
||||
Claims *CustomClaims
|
||||
IsValid bool
|
||||
IsExpired bool
|
||||
}
|
||||
|
||||
type jwtManager struct {
|
||||
secret string
|
||||
accessExpiry time.Duration
|
||||
refreshExpiry time.Duration
|
||||
secret string
|
||||
tokenExpiry time.Duration
|
||||
}
|
||||
|
||||
var (
|
||||
@@ -30,76 +23,59 @@ var (
|
||||
once sync.Once
|
||||
)
|
||||
|
||||
// InitJwt 初始化全局 JWT 配置,只能调用一次
|
||||
// InitJwt 初始化全局 JWT 配置
|
||||
func InitJwt() {
|
||||
once.Do(func() {
|
||||
manager = &jwtManager{
|
||||
secret: conf.GetConf().JWT.Secret,
|
||||
accessExpiry: conf.GetConf().JWT.AccessExpiry,
|
||||
refreshExpiry: conf.GetConf().JWT.RefreshExpiry,
|
||||
secret: conf.GetConf().JWT.Secret,
|
||||
tokenExpiry: conf.GetConf().JWT.AccessExpiry, // 直接当唯一 token
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// CreateAccessToken 全局函数创建 Access Token
|
||||
func CreateAccessToken(userID int64) (string, error) {
|
||||
return manager.createToken(userID, manager.accessExpiry)
|
||||
// CreateToken 创建 JWT
|
||||
func CreateToken(userID int64) (string, error) {
|
||||
if manager == nil {
|
||||
return "", jwt.ErrTokenInvalidClaims
|
||||
}
|
||||
return manager.createToken(userID)
|
||||
}
|
||||
|
||||
// CreateRefreshToken 全局函数创建 Refresh Token
|
||||
func CreateRefreshToken(userID int64) (string, error) {
|
||||
return manager.createToken(userID, manager.refreshExpiry)
|
||||
}
|
||||
|
||||
// VerifyToken 全局函数验证 Token
|
||||
func VerifyToken(tokenString string) TokenResult {
|
||||
result := TokenResult{IsValid: false, IsExpired: false}
|
||||
|
||||
// VerifyToken 校验 JWT(合法 or 不合法)
|
||||
func VerifyToken(tokenString string) (*CustomClaims, bool) {
|
||||
if tokenString == "" || manager == nil {
|
||||
return result
|
||||
return nil, false
|
||||
}
|
||||
|
||||
token, err := jwt.ParseWithClaims(tokenString, &CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
|
||||
return []byte(manager.secret), nil
|
||||
})
|
||||
|
||||
if token == nil {
|
||||
return result
|
||||
if err != nil || !token.Valid {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
claims, ok := token.Claims.(*CustomClaims)
|
||||
if !ok {
|
||||
return result
|
||||
return nil, false
|
||||
}
|
||||
|
||||
if err != nil || !token.Valid {
|
||||
return result
|
||||
}
|
||||
|
||||
result.Claims = claims
|
||||
result.IsValid = true
|
||||
if claims.ExpiresAt != nil && time.Now().After(claims.ExpiresAt.Time) {
|
||||
result.IsExpired = true
|
||||
}
|
||||
return result
|
||||
return claims, true
|
||||
}
|
||||
|
||||
// 内部方法,生成 Token
|
||||
func (j *jwtManager) createToken(userID int64, expiry time.Duration) (string, error) {
|
||||
func (j *jwtManager) createToken(userID int64) (string, error) {
|
||||
now := time.Now()
|
||||
|
||||
claims := &CustomClaims{
|
||||
UserID: userID,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
IssuedAt: jwt.NewNumericDate(now),
|
||||
},
|
||||
}
|
||||
|
||||
switch {
|
||||
case expiry > 0:
|
||||
claims.ExpiresAt = jwt.NewNumericDate(time.Now().Add(expiry))
|
||||
case expiry == -1:
|
||||
claims.ExpiresAt = nil // 永不过期
|
||||
default:
|
||||
claims.ExpiresAt = jwt.NewNumericDate(time.Now().Add(time.Hour))
|
||||
// 只有大于 0 才设置过期时间
|
||||
if j.tokenExpiry > 0 {
|
||||
claims.ExpiresAt = jwt.NewNumericDate(now.Add(j.tokenExpiry))
|
||||
}
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
|
||||
@@ -135,3 +135,10 @@ func DateToString(d pgtype.Date) string {
|
||||
}
|
||||
return d.Time.Format("2006-01-02")
|
||||
}
|
||||
|
||||
func Int32ToPgInt4(value int32) pgtype.Int4 {
|
||||
return pgtype.Int4{
|
||||
Int32: value,
|
||||
Valid: true,
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user