Files
bj_power/bj_power_wms_client/internal/proxy/proxy.go
T
2026-08-28 15:06:01 +08:00

31 lines
884 B
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 proxy
import (
"fmt"
"net/http"
"net/http/httputil"
"net/url"
)
// New 创建指向 WMS 后端的反向代理。
// 请求转发时统一注入内部 API TokenX-API-TOKEN),由 WMS 依此鉴权;
// 响应头默认全量透传(含滑动续签的 X-Renewed-Token,由 WMS 写入)。
func New(upstream, apiToken string) *httputil.ReverseProxy {
target, err := url.Parse(upstream)
if err != nil {
panic(fmt.Sprintf("WmsAddr 配置非法: %v", err))
}
rp := httputil.NewSingleHostReverseProxy(target)
origDirector := rp.Director
rp.Director = func(req *http.Request) {
origDirector(req)
req.Host = target.Host
if apiToken != "" {
req.Header.Set("X-API-TOKEN", apiToken)
}
}
rp.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {
http.Error(w, "WMS 服务不可达: "+err.Error(), http.StatusBadGateway)
}
return rp
}