Files
sub2api/backend/internal/service/gateway_billing_header.go
T
李建琦 6d655c9903
Release / update-version (push) Has been cancelled
Release / build-frontend (push) Has been cancelled
Release / release (push) Has been cancelled
Release / sync-version-file (push) Has been cancelled
CI / shell (push) Canceled after 0s
CI / test (push) Canceled after 0s
CI / frontend (push) Canceled after 0s
CI / golangci-lint (push) Canceled after 0s
Security Scan / backend-security (push) Canceled after 0s
Security Scan / frontend-security (push) Canceled after 0s
Sub2API v1.0 - AI API 网关(二开初始版本,基于上游 Wei-Shaw/sub2api)
2026-08-21 18:30:13 +08:00

49 lines
1.4 KiB
Go

package service
import (
"fmt"
"regexp"
"strings"
"github.com/tidwall/gjson"
"github.com/tidwall/sjson"
)
// ccVersionInBillingRe matches the semver part of cc_version (X.Y.Z), preserving
// the trailing message-derived suffix (e.g. ".c02") if present.
var ccVersionInBillingRe = regexp.MustCompile(`cc_version=\d+\.\d+\.\d+`)
// syncBillingHeaderVersion rewrites cc_version in x-anthropic-billing-header
// system text blocks to match the version extracted from userAgent.
// Only touches system array blocks whose text starts with "x-anthropic-billing-header".
func syncBillingHeaderVersion(body []byte, userAgent string) []byte {
version := ExtractCLIVersion(userAgent)
if version == "" {
return body
}
systemResult := gjson.GetBytes(body, "system")
if !systemResult.Exists() || !systemResult.IsArray() {
return body
}
replacement := "cc_version=" + version
idx := 0
systemResult.ForEach(func(_, item gjson.Result) bool {
text := item.Get("text")
if text.Exists() && text.Type == gjson.String &&
strings.HasPrefix(text.String(), "x-anthropic-billing-header") {
newText := ccVersionInBillingRe.ReplaceAllString(text.String(), replacement)
if newText != text.String() {
if updated, err := sjson.SetBytes(body, fmt.Sprintf("system.%d.text", idx), newText); err == nil {
body = updated
}
}
}
idx++
return true
})
return body
}