Files
Mycontent/soul-api/internal/handler/request_origin.go
2026-04-13 14:32:32 +08:00

60 lines
1.6 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package handler
import (
"encoding/json"
"strings"
"github.com/gin-gonic/gin"
)
// PublicOriginFromRequest 根据当前请求还原对外访问根 URLhttps://souldev.xxx
// 用于开发/预览域名与 API_BASE_URL常为正式 soulapi不一致时头像与 mp_config.apiDomain 与浏览器 Host 对齐。
func PublicOriginFromRequest(c *gin.Context) string {
if c == nil || c.Request == nil {
return ""
}
proto := strings.TrimSpace(strings.ToLower(c.GetHeader("X-Forwarded-Proto")))
switch proto {
case "":
if c.Request.TLS != nil {
proto = "https"
} else {
proto = "http"
}
case "http", "https":
default:
proto = "https"
}
host := strings.TrimSpace(c.Request.Host)
if xfh := c.GetHeader("X-Forwarded-Host"); xfh != "" {
host = strings.TrimSpace(strings.Split(xfh, ",")[0])
}
if host == "" {
return ""
}
return proto + "://" + host
}
// patchMiniprogramConfigJSONOrigin 深拷贝 JSON 响应体并将 mpConfig.apiDomain 改为当前请求的公网 origin若有
// 避免 souldev 请求却下发 soulapi 域名导致小程序拼接静态资源/头像域名错误。
func patchMiniprogramConfigJSONOrigin(c *gin.Context, body interface{}) interface{} {
origin := PublicOriginFromRequest(c)
if origin == "" || body == nil {
return body
}
b, err := json.Marshal(body)
if err != nil {
return body
}
var m map[string]interface{}
if err := json.Unmarshal(b, &m); err != nil {
return body
}
mp, ok := m["mpConfig"].(map[string]interface{})
if !ok || mp == nil {
return m
}
mp["apiDomain"] = origin
return m
}