- api/common/v1/tools.go 契约 + internal/controller/common 实现:uuid/md5/random/time/ip - cmd.go 注册 /api/common/v1 公开分组(无鉴权),复用 common/tools Go 包 - 修复 gtime v2.10.2 坑:Format 为 PHP 风格,Go layout 须用 Layout(),timex 封装为 Layout 语义 - 冒烟测试 5 端点全部通过;AGENTS.md / PROJECT_STRUCTURE.md / change-log 同步更新
67 lines
2.2 KiB
Go
67 lines
2.2 KiB
Go
// Package common implements the public common API (/api/common/v1).
|
|
// These controllers are thin adapters over the common/tools Go packages and
|
|
// require no authentication.
|
|
package common
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.com/gogf/gf/v2/frame/g"
|
|
|
|
commonv1 "service.xpcool.com/api/common/v1"
|
|
"service.xpcool.com/common/tools/ip"
|
|
"service.xpcool.com/common/tools/md5"
|
|
"service.xpcool.com/common/tools/random"
|
|
"service.xpcool.com/common/tools/timex"
|
|
"service.xpcool.com/common/tools/uuid"
|
|
)
|
|
|
|
// Controller implements the /api/common/v1 endpoints.
|
|
type Controller struct{}
|
|
|
|
// New creates a common API controller.
|
|
func New() *Controller { return &Controller{} }
|
|
|
|
// UUID generates a unique ID (32-char by default, 8-char when short=true).
|
|
func (c *Controller) UUID(ctx context.Context, req *commonv1.UUIDReq) (res *commonv1.UUIDRes, err error) {
|
|
if req.Short {
|
|
return &commonv1.UUIDRes{UUID: uuid.Short(8)}, nil
|
|
}
|
|
return &commonv1.UUIDRes{UUID: uuid.New()}, nil
|
|
}
|
|
|
|
// MD5 computes the MD5 digest of the given text.
|
|
func (c *Controller) MD5(ctx context.Context, req *commonv1.MD5Req) (res *commonv1.MD5Res, err error) {
|
|
return &commonv1.MD5Res{MD5: md5.Md5Hex(req.Text)}, nil
|
|
}
|
|
|
|
// Random generates a random string of the requested type and length.
|
|
func (c *Controller) Random(ctx context.Context, req *commonv1.RandomReq) (res *commonv1.RandomRes, err error) {
|
|
var value string
|
|
switch req.Type {
|
|
case "digits":
|
|
value = random.Digits(req.Length)
|
|
case "letters":
|
|
value = random.Letters(req.Length)
|
|
default:
|
|
value = random.String(req.Length)
|
|
}
|
|
return &commonv1.RandomRes{Value: value}, nil
|
|
}
|
|
|
|
// Time returns the current server timestamp and formatted time.
|
|
func (c *Controller) Time(ctx context.Context, req *commonv1.TimeReq) (res *commonv1.TimeRes, err error) {
|
|
now := timex.Now()
|
|
return &commonv1.TimeRes{
|
|
Timestamp: now.Timestamp(),
|
|
DateTime: now.Layout(timex.LayoutDateTime),
|
|
Date: now.Layout(timex.LayoutDate),
|
|
}, nil
|
|
}
|
|
|
|
// IP returns the caller's IP and whether it is an internal address.
|
|
func (c *Controller) IP(ctx context.Context, req *commonv1.IPReq) (res *commonv1.IPRes, err error) {
|
|
clientIP := g.RequestFromCtx(ctx).GetClientIp()
|
|
return &commonv1.IPRes{IP: clientIP, Internal: ip.IsInternal(clientIP)}, nil
|
|
}
|