fix: 修复地理位置GBK编码问题

This commit is contained in:
2026-03-04 18:30:31 +08:00
parent 00a0a01b17
commit 90cf3990d3

View File

@@ -8,6 +8,9 @@ import (
"math/rand" "math/rand"
"net/http" "net/http"
"time" "time"
"golang.org/x/text/encoding/simplifiedchinese"
"golang.org/x/text/transform"
) )
// LocationResponse represents the response from IP location API // LocationResponse represents the response from IP location API
@@ -74,7 +77,9 @@ func GetLocation(ctx context.Context, ip string) (province string, city string,
return "", "", fmt.Errorf("request failed with status: %d", resp.StatusCode) return "", "", fmt.Errorf("request failed with status: %d", resp.StatusCode)
} }
body, err := io.ReadAll(resp.Body) // API返回的是GBK编码需要转换为UTF-8
utf8Reader := transform.NewReader(resp.Body, simplifiedchinese.GBK.NewDecoder())
body, err := io.ReadAll(utf8Reader)
if err != nil { if err != nil {
return "", "", fmt.Errorf("read response failed: %w", err) return "", "", fmt.Errorf("read response failed: %w", err)
} }