chore(init): 初始化解忧商行项目并完成 Phase 0 基座
This commit is contained in:
@@ -0,0 +1,132 @@
|
||||
package crypto
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"io"
|
||||
)
|
||||
|
||||
// Encryptor 字段加密器接口。Encrypt 永远用主密钥,Decrypt 先试主密钥、失败试 legacy 密钥。
|
||||
type Encryptor interface {
|
||||
Encrypt(plaintext string) (string, error)
|
||||
Decrypt(ciphertext string) (string, error)
|
||||
}
|
||||
|
||||
// aesKey 持有一个 AES-GCM 密钥及其 cipher。
|
||||
type aesKey struct {
|
||||
key []byte
|
||||
}
|
||||
|
||||
func newAESKey(key string) (*aesKey, error) {
|
||||
keyBytes := []byte(key)
|
||||
if len(keyBytes) != 16 && len(keyBytes) != 24 && len(keyBytes) != 32 {
|
||||
return nil, errors.New("invalid key length: must be 16, 24, or 32 bytes")
|
||||
}
|
||||
return &aesKey{key: keyBytes}, nil
|
||||
}
|
||||
|
||||
// FieldEncryptor 持有主密钥 + 可选 legacy 密钥列表。
|
||||
// Encrypt 永远用 primary;Decrypt 先试 primary,gcm.Open 认证失败依次试 legacy,
|
||||
// 用于密钥轮换期间透明解出旧密文。
|
||||
type FieldEncryptor struct {
|
||||
primary *aesKey
|
||||
legacy []*aesKey
|
||||
}
|
||||
|
||||
// NewFieldEncryptor 创建字段加密器。primary 为主密钥,legacy 为可选的旧密钥(用于回退解密)。
|
||||
func NewFieldEncryptor(primary string, legacy ...string) (*FieldEncryptor, error) {
|
||||
primaryKey, err := newAESKey(primary)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
legacyKeys := make([]*aesKey, 0, len(legacy))
|
||||
for _, l := range legacy {
|
||||
if l == "" || l == primary {
|
||||
continue
|
||||
}
|
||||
k, err := newAESKey(l)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
legacyKeys = append(legacyKeys, k)
|
||||
}
|
||||
return &FieldEncryptor{primary: primaryKey, legacy: legacyKeys}, nil
|
||||
}
|
||||
|
||||
// Encrypt 使用 AES-GCM 加密明文,输出 base64(nonce || ciphertext || gcmTag)。
|
||||
func (e *FieldEncryptor) Encrypt(plaintext string) (string, error) {
|
||||
if plaintext == "" {
|
||||
return "", nil
|
||||
}
|
||||
gcm, err := e.gcm(e.primary)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
nonce := make([]byte, gcm.NonceSize())
|
||||
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
|
||||
return "", err
|
||||
}
|
||||
ciphertext := gcm.Seal(nonce, nonce, []byte(plaintext), nil)
|
||||
return base64.StdEncoding.EncodeToString(ciphertext), nil
|
||||
}
|
||||
|
||||
// Decrypt 解密密文。先试主密钥,gcm.Open 认证失败依次试 legacy 密钥。
|
||||
func (e *FieldEncryptor) Decrypt(ciphertext string) (string, error) {
|
||||
if ciphertext == "" {
|
||||
return "", nil
|
||||
}
|
||||
decoded, err := base64.StdEncoding.DecodeString(ciphertext)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
for _, k := range append([]*aesKey{e.primary}, e.legacy...) {
|
||||
plaintext, err := decryptWithKey(k, decoded)
|
||||
if err == nil {
|
||||
return plaintext, nil
|
||||
}
|
||||
}
|
||||
return "", errors.New("decrypt failed: no matching key")
|
||||
}
|
||||
|
||||
func (e *FieldEncryptor) gcm(k *aesKey) (cipher.AEAD, error) {
|
||||
block, err := aes.NewCipher(k.key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return cipher.NewGCM(block)
|
||||
}
|
||||
|
||||
func decryptWithKey(k *aesKey, decoded []byte) (string, error) {
|
||||
block, err := aes.NewCipher(k.key)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
gcm, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
nonceSize := gcm.NonceSize()
|
||||
if len(decoded) < nonceSize {
|
||||
return "", errors.New("ciphertext too short")
|
||||
}
|
||||
nonce, body := decoded[:nonceSize], decoded[nonceSize:]
|
||||
plaintext, err := gcm.Open(nil, nonce, body, nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(plaintext), nil
|
||||
}
|
||||
|
||||
// MockEncryptor 测试用直通加密器,明文不加密。
|
||||
type MockEncryptor struct{}
|
||||
|
||||
func (e *MockEncryptor) Encrypt(plaintext string) (string, error) {
|
||||
return plaintext, nil
|
||||
}
|
||||
|
||||
func (e *MockEncryptor) Decrypt(ciphertext string) (string, error) {
|
||||
return ciphertext, nil
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package crypto
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const (
|
||||
testPrimaryKey = "0123456789abcdef0123456789abcdef" // 32 字节
|
||||
testLegacyKey = "hfb-sys-2024-secret-key-32bytes!"
|
||||
)
|
||||
|
||||
func TestFieldEncryptorRoundTrip(t *testing.T) {
|
||||
enc, err := NewFieldEncryptor(testPrimaryKey)
|
||||
if err != nil {
|
||||
t.Fatalf("NewFieldEncryptor() error = %v", err)
|
||||
}
|
||||
cases := []string{"", "张三", "110101199003077734", "6222021234567890", "with spaces and 中文"}
|
||||
for _, plain := range cases {
|
||||
cipher, err := enc.Encrypt(plain)
|
||||
if err != nil {
|
||||
t.Fatalf("Encrypt(%q) error = %v", plain, err)
|
||||
}
|
||||
got, err := enc.Decrypt(cipher)
|
||||
if err != nil {
|
||||
t.Fatalf("Decrypt() error = %v", err)
|
||||
}
|
||||
if got != plain {
|
||||
t.Fatalf("round-trip mismatch: got %q, want %q", got, plain)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFieldEncryptorEmptyStringPassthrough(t *testing.T) {
|
||||
enc, _ := NewFieldEncryptor(testPrimaryKey)
|
||||
cipher, err := enc.Encrypt("")
|
||||
if err != nil {
|
||||
t.Fatalf("Encrypt(\"\") error = %v", err)
|
||||
}
|
||||
if cipher != "" {
|
||||
t.Fatalf("Encrypt(\"\") = %q, want empty", cipher)
|
||||
}
|
||||
got, err := enc.Decrypt("")
|
||||
if err != nil {
|
||||
t.Fatalf("Decrypt(\"\") error = %v", err)
|
||||
}
|
||||
if got != "" {
|
||||
t.Fatalf("Decrypt(\"\") = %q, want empty", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestFieldEncryptorLegacyFallback 验证旧密钥加密的密文,新 FieldEncryptor(含 legacy)能解出。
|
||||
func TestFieldEncryptorLegacyFallback(t *testing.T) {
|
||||
legacyEnc, _ := NewFieldEncryptor(testLegacyKey)
|
||||
plain := "110101199003077734"
|
||||
cipher, err := legacyEnc.Encrypt(plain)
|
||||
if err != nil {
|
||||
t.Fatalf("legacy Encrypt() error = %v", err)
|
||||
}
|
||||
|
||||
// 新加密器:primary 不同,legacy 含旧密钥
|
||||
primaryEnc, err := NewFieldEncryptor(testPrimaryKey, testLegacyKey)
|
||||
if err != nil {
|
||||
t.Fatalf("NewFieldEncryptor(primary, legacy) error = %v", err)
|
||||
}
|
||||
got, err := primaryEnc.Decrypt(cipher)
|
||||
if err != nil {
|
||||
t.Fatalf("Decrypt() with legacy fallback error = %v", err)
|
||||
}
|
||||
if got != plain {
|
||||
t.Fatalf("legacy fallback mismatch: got %q, want %q", got, plain)
|
||||
}
|
||||
}
|
||||
|
||||
// TestFieldEncryptorNoLegacyFailsOnOldCiphertext 验证无 legacy 时解旧密文失败。
|
||||
func TestFieldEncryptorNoLegacyFailsOnOldCiphertext(t *testing.T) {
|
||||
legacyEnc, _ := NewFieldEncryptor(testLegacyKey)
|
||||
cipher, _ := legacyEnc.Encrypt("secret")
|
||||
|
||||
primaryOnly, _ := NewFieldEncryptor(testPrimaryKey)
|
||||
if _, err := primaryOnly.Decrypt(cipher); err == nil {
|
||||
t.Fatal("Decrypt() with no legacy should fail on old ciphertext")
|
||||
}
|
||||
}
|
||||
|
||||
// TestFieldEncryptorDecryptGarbageFails 验证非密文输入解密失败。
|
||||
func TestFieldEncryptorDecryptGarbageFails(t *testing.T) {
|
||||
enc, _ := NewFieldEncryptor(testPrimaryKey)
|
||||
cases := []string{"not-base64!!!", "dG9vIHNob3J0"} // 非 base64 / 解码后太短
|
||||
for _, c := range cases {
|
||||
if _, err := enc.Decrypt(c); err == nil {
|
||||
t.Fatalf("Decrypt(%q) should fail", c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewFieldEncryptorInvalidKeyLength(t *testing.T) {
|
||||
// AES 只接受 16/24/32 字节,其余长度必须失败
|
||||
cases := []int{0, 1, 15, 17, 23, 25, 31, 33, 40}
|
||||
for _, n := range cases {
|
||||
key := string(make([]byte, n)) // n 个零字节
|
||||
if _, err := NewFieldEncryptor(key); err == nil {
|
||||
t.Fatalf("NewFieldEncryptor(len=%d) should fail on invalid length", n)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestNewFieldEncryptorDedupsLegacyKey 验证 legacy 等于 primary 时被忽略(避免无效回退)。
|
||||
func TestNewFieldEncryptorDedupsLegacyKey(t *testing.T) {
|
||||
enc, err := NewFieldEncryptor(testPrimaryKey, testPrimaryKey, "")
|
||||
if err != nil {
|
||||
t.Fatalf("NewFieldEncryptor() error = %v", err)
|
||||
}
|
||||
if len(enc.legacy) != 0 {
|
||||
t.Fatalf("legacy should be empty after dedup, got %d", len(enc.legacy))
|
||||
}
|
||||
}
|
||||
|
||||
func TestMockEncryptorPassthrough(t *testing.T) {
|
||||
m := &MockEncryptor{}
|
||||
plain := "明文直通"
|
||||
cipher, err := m.Encrypt(plain)
|
||||
if err != nil || cipher != plain {
|
||||
t.Fatalf("MockEncryptor.Encrypt(%q) = (%q,%v), want (%q,nil)", plain, cipher, err, plain)
|
||||
}
|
||||
got, err := m.Decrypt(cipher)
|
||||
if err != nil || got != plain {
|
||||
t.Fatalf("MockEncryptor.Decrypt(%q) = (%q,%v), want (%q,nil)", cipher, got, err, plain)
|
||||
}
|
||||
}
|
||||
|
||||
// TestFieldEncryptorCipherFormatStable 验证密文是 base64(nonce||ct||tag),格式与历史硬编码实现一致。
|
||||
// 确保迁移后存量密文(旧实现加密)能被新实现的 Decrypt 正确解析。
|
||||
func TestFieldEncryptorCipherFormatStable(t *testing.T) {
|
||||
enc, _ := NewFieldEncryptor(testLegacyKey)
|
||||
cipher, _ := enc.Encrypt("test")
|
||||
// base64 解码后长度 > nonce(12) + tag(16) = 28,且明文长度 4 → 总长 32
|
||||
decoded, err := base64.StdEncoding.DecodeString(cipher)
|
||||
if err != nil {
|
||||
t.Fatalf("cipher not valid base64: %v", err)
|
||||
}
|
||||
if len(decoded) <= 28 {
|
||||
t.Fatalf("decoded length = %d, want > 28 (nonce+tag)", len(decoded))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package crypto
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// FingerprintHMAC 生成用于唯一性盲索引的稳定 HMAC-SHA256 指纹。
|
||||
// secret 为空时退化为带域前缀的 SHA-256,仅用于本地/测试环境。
|
||||
func FingerprintHMAC(secret, domain, value string) string {
|
||||
payload := strings.TrimSpace(domain) + ":" + strings.TrimSpace(value)
|
||||
if strings.TrimSpace(secret) == "" {
|
||||
sum := sha256.Sum256([]byte(payload))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
mac := hmac.New(sha256.New, []byte(secret))
|
||||
_, _ = mac.Write([]byte(payload))
|
||||
return hex.EncodeToString(mac.Sum(nil))
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package money
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
)
|
||||
|
||||
// Round 将金额四舍五入到角(0.1元),统一全项目金额精度
|
||||
// 例如:12.34 -> 12.3, 12.36 -> 12.4, 12.35 -> 12.4
|
||||
func Round(value float64) float64 {
|
||||
return math.Round(value*10) / 10
|
||||
}
|
||||
|
||||
// ToCent 将元转换为分(整数),用于存储。
|
||||
// 12.34 元 -> 1234 分
|
||||
func ToCent(yuan float64) int64 {
|
||||
return int64(math.Round(yuan * 100))
|
||||
}
|
||||
|
||||
// ToDisplayYuan 将分转换为按角精度展示的元值。
|
||||
// 1234 分 -> 12.3 元
|
||||
func ToDisplayYuan(cent int64) float64 {
|
||||
return Round(float64(cent) / 100)
|
||||
}
|
||||
|
||||
// Format 格式化分为字符串(角精度,保留1位小数)
|
||||
// 1234 分 -> "12.3"
|
||||
// 1230 分 -> "12.3"
|
||||
func Format(cent int64) string {
|
||||
return fmt.Sprintf("%.1f", ToDisplayYuan(cent))
|
||||
}
|
||||
|
||||
// FormatWithSymbol 格式化分为带符号的字符串
|
||||
// 123分 -> "¥12.3"
|
||||
func FormatWithSymbol(cent int64) string {
|
||||
return "¥" + Format(cent)
|
||||
}
|
||||
|
||||
// Min 返回两个金额中较小的值(角精度,兼容旧代码)
|
||||
func Min(a, b float64) float64 {
|
||||
if a < b {
|
||||
return Round(a)
|
||||
}
|
||||
return Round(b)
|
||||
}
|
||||
|
||||
// Max 返回两个金额中较大的值(角精度,兼容旧代码)
|
||||
func Max(a, b float64) float64 {
|
||||
if a > b {
|
||||
return Round(a)
|
||||
}
|
||||
return Round(b)
|
||||
}
|
||||
|
||||
// MinCent 返回两个分值中较小的值
|
||||
func MinCent(a, b int64) int64 {
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// MaxCent 返回两个分值中较大的值
|
||||
func MaxCent(a, b int64) int64 {
|
||||
if a > b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
package money
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestToCent(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
yuan float64
|
||||
want int64
|
||||
}{
|
||||
{"12.3元转1230分", 12.3, 1230},
|
||||
{"12.34元转1234分", 12.34, 1234},
|
||||
{"12.36元转1236分", 12.36, 1236},
|
||||
{"0.1元转10分", 0.1, 10},
|
||||
{"100元转10000分", 100.0, 10000},
|
||||
{"零值", 0.0, 0},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := ToCent(tt.yuan)
|
||||
if got != tt.want {
|
||||
t.Errorf("ToCent(%v) = %v, want %v", tt.yuan, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestToDisplayYuan(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
cent int64
|
||||
want float64
|
||||
}{
|
||||
{"123分展示1.2元", 123, 1.2},
|
||||
{"1234分展示12.3元", 1234, 12.3},
|
||||
{"1236分展示12.4元", 1236, 12.4},
|
||||
{"10分展示0.1元", 10, 0.1},
|
||||
{"1000分展示10.0元", 1000, 10.0},
|
||||
{"零值", 0, 0.0},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := ToDisplayYuan(tt.cent)
|
||||
if got != tt.want {
|
||||
t.Errorf("ToDisplayYuan(%v) = %v, want %v", tt.cent, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormat(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
cent int64
|
||||
want string
|
||||
}{
|
||||
{"123分格式化", 123, "1.2"},
|
||||
{"1234分格式化", 1234, "12.3"},
|
||||
{"1236分格式化", 1236, "12.4"},
|
||||
{"10分格式化", 10, "0.1"},
|
||||
{"1000分格式化", 1000, "10.0"},
|
||||
{"零值格式化", 0, "0.0"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := Format(tt.cent)
|
||||
if got != tt.want {
|
||||
t.Errorf("Format(%v) = %v, want %v", tt.cent, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatWithSymbol(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
cent int64
|
||||
want string
|
||||
}{
|
||||
{"123分带符号", 123, "¥1.2"},
|
||||
{"1000分带符号", 1000, "¥10.0"},
|
||||
{"零值带符号", 0, "¥0.0"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := FormatWithSymbol(tt.cent)
|
||||
if got != tt.want {
|
||||
t.Errorf("FormatWithSymbol(%v) = %v, want %v", tt.cent, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRound(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
value float64
|
||||
want float64
|
||||
}{
|
||||
{"12.34舍入到12.3", 12.34, 12.3},
|
||||
{"12.36舍入到12.4", 12.36, 12.4},
|
||||
{"12.35舍入到12.4", 12.35, 12.4},
|
||||
{"0.05舍入到0.1", 0.05, 0.1},
|
||||
{"0.04舍入到0.0", 0.04, 0.0},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := Round(tt.value)
|
||||
if got != tt.want {
|
||||
t.Errorf("Round(%v) = %v, want %v", tt.value, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMinMax(t *testing.T) {
|
||||
t.Run("Min", func(t *testing.T) {
|
||||
if got := Min(100, 200); got != 100 {
|
||||
t.Errorf("Min(100, 200) = %v, want 100", got)
|
||||
}
|
||||
if got := Min(200, 100); got != 100 {
|
||||
t.Errorf("Min(200, 100) = %v, want 100", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Max", func(t *testing.T) {
|
||||
if got := Max(100, 200); got != 200 {
|
||||
t.Errorf("Max(100, 200) = %v, want 200", got)
|
||||
}
|
||||
if got := Max(200, 100); got != 200 {
|
||||
t.Errorf("Max(200, 100) = %v, want 200", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// 测试双向转换的精度
|
||||
func TestRoundTrip(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
originalYuan float64
|
||||
expectDisplay float64
|
||||
}{
|
||||
{"12.3元往返", 12.3, 12.3},
|
||||
{"12.34元往返(展示到角)", 12.34, 12.3},
|
||||
{"100.0元往返", 100.0, 100.0},
|
||||
{"0.1元往返", 0.1, 0.1},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
cent := ToCent(tt.originalYuan)
|
||||
got := ToDisplayYuan(cent)
|
||||
if got != tt.expectDisplay {
|
||||
t.Errorf("往返转换:%v元 -> %v分 -> %v元, 期望 %v元",
|
||||
tt.originalYuan, cent, got, tt.expectDisplay)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package response
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const contextResponseCode = "response_code"
|
||||
|
||||
type Body struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
Data any `json:"data,omitempty"`
|
||||
}
|
||||
|
||||
func OK(c *gin.Context, data any) {
|
||||
c.JSON(http.StatusOK, Body{
|
||||
Code: "ok",
|
||||
Message: "ok",
|
||||
Data: data,
|
||||
})
|
||||
}
|
||||
|
||||
func Created(c *gin.Context, data any) {
|
||||
c.JSON(http.StatusCreated, Body{
|
||||
Code: "ok",
|
||||
Message: "created",
|
||||
Data: data,
|
||||
})
|
||||
}
|
||||
|
||||
func Error(c *gin.Context, status int, code, message string) {
|
||||
if status >= http.StatusInternalServerError && len(c.Errors) == 0 {
|
||||
RecordError(c, fmt.Errorf("未记录原始错误: %s", code))
|
||||
}
|
||||
c.Set(contextResponseCode, code)
|
||||
c.JSON(status, Body{
|
||||
Code: code,
|
||||
Message: message,
|
||||
})
|
||||
}
|
||||
|
||||
// RecordError 保存原始错误,供统一请求日志记录服务端故障原因。
|
||||
func RecordError(c *gin.Context, err error) {
|
||||
if c == nil || err == nil || errors.Is(err, context.Canceled) {
|
||||
return
|
||||
}
|
||||
for _, item := range c.Errors {
|
||||
if errors.Is(item.Err, err) {
|
||||
return
|
||||
}
|
||||
}
|
||||
_ = c.Error(err)
|
||||
}
|
||||
|
||||
// CodeFromContext 返回已经写入响应的稳定业务错误码。
|
||||
func CodeFromContext(c *gin.Context) string {
|
||||
value, ok := c.Get(contextResponseCode)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
code, _ := value.(string)
|
||||
return code
|
||||
}
|
||||
|
||||
func BadRequest(c *gin.Context, message string) {
|
||||
Error(c, http.StatusBadRequest, "bad_request", message)
|
||||
}
|
||||
|
||||
func Forbidden(c *gin.Context, message string) {
|
||||
Error(c, http.StatusForbidden, "forbidden", message)
|
||||
}
|
||||
|
||||
func Unauthorized(c *gin.Context, message string) {
|
||||
Error(c, http.StatusUnauthorized, "unauthorized", message)
|
||||
}
|
||||
|
||||
func ServiceUnavailable(c *gin.Context, message string) {
|
||||
Error(c, http.StatusServiceUnavailable, "service_unavailable", message)
|
||||
}
|
||||
|
||||
func NotFound(c *gin.Context, message string) {
|
||||
Error(c, http.StatusNotFound, "not_found", message)
|
||||
}
|
||||
|
||||
func InternalServerError(c *gin.Context, message string) {
|
||||
Error(c, http.StatusInternalServerError, "internal_server_error", message)
|
||||
}
|
||||
Reference in New Issue
Block a user