refactor(client): 提取 shouldAppendJSONSuffix 方法,保留 raw 路径特例

This commit is contained in:
camelliamc 2026-06-14 21:19:03 +08:00
parent 6583d09f04
commit 0a6e0f0b94
1 changed files with 24 additions and 5 deletions

View File

@ -48,14 +48,12 @@ func New() (*Client, error) {
func (c *Client) Do(method, path string, body interface{}, query url.Values) (*output.Envelope, error) {
// Append .json suffix if not already present (GitLink API convention)
// Handle paths that may already contain query strings (e.g., /path?key=val)
if !c.SkipJSONSuffix {
if c.shouldAppendJSONSuffix(path) {
if idx := strings.Index(path, "?"); idx != -1 {
basePath := path[:idx]
queryStr := path[idx:]
if !strings.HasSuffix(basePath, ".json") {
path = basePath + ".json" + queryStr
}
} else if !strings.HasSuffix(path, ".json") {
path = basePath + ".json" + queryStr
} else {
path += ".json"
}
}
@ -225,3 +223,24 @@ func lookupStatusInfo(code int) statusInfo {
message: fmt.Sprintf("API 返回错误码 %d", code),
}
}
// shouldAppendJSONSuffix reports whether the .json suffix should be appended to path.
// Returns false (skip append) when:
// - c.SkipJSONSuffix is set (explicit opt-out for non-JSON endpoints such as gateway)
// - path already ends with .json
// - path matches the raw content pattern (e.g., /api/:owner/:repo/raw/...)
func (c *Client) shouldAppendJSONSuffix(path string) bool {
if c.SkipJSONSuffix {
return false
}
if strings.HasSuffix(path, ".json") {
return false
}
parts := strings.Split(strings.Trim(path, "/"), "/")
for i, part := range parts {
if part == "raw" && i >= 2 && i+2 < len(parts) {
return false
}
}
return true
}