我有一個使用 Gin gonic 的 Go 應(yīng)用程序和一個 Nginx 反向代理,它們將流量發(fā)送到 domain.com 上的另一個應(yīng)用程序,并將所有 *.domain.com 子域流量直接發(fā)送到我的 Go 應(yīng)用程序。然后我的 Go 應(yīng)用程序有一個中間件,它將讀取 nginx 從 Context 傳遞給它的主機名,并允許我的處理程序知道正在請求哪個子域,并為所述子域返回正確的數(shù)據(jù)和 cookie。這是一個非常簡單的設(shè)置,從我在郵遞員中的測試來看,它似乎工作正常,因為我所有的子域中的所有路由都是相同的,所以這樣我只能為所有子域使用一個路由器,而不是每個子域使用一個路由器?,F(xiàn)在,當我嘗試進行端到端測試時,我的大問題就來了。我正在這樣設(shè)置我的測試: router := initRouter() w := httptest.NewRecorder() req, _ := http.NewRequest("POST", "/api/login", bytes.NewBuffer(jsonLogin)) req.Header.Set("Content-Type", "application/json") router.ServeHTTP(w, req) assert.Equal(t, 200, w.Code)返回initRouter()一個加載了我所有路由和中間件的 gin 引擎,其余的作為基本測試設(shè)置。顯然,測試將失敗,因為 gin 上下文永遠不會從上下文中接收子域,并且表現(xiàn)得好像所有內(nèi)容都來自 localhost:8000。有沒有辦法:“模擬”一個子域,以便路由器認為呼叫來自 foo.localhost.com 而不是 localhost設(shè)置我的測試套裝,以便通過 nginx 路由測試請求。我更喜歡解決方案 1,因為這將是設(shè)置/維護的一團糟。
1 回答

POPMUISE
TA貢獻1765條經(jīng)驗 獲得超5個贊
http.NewRequest 返回的請求不適合直接傳遞給ServeHTTP。請改用 httptest.NewRequest 返回的一個。
只需直接設(shè)置Host 字段:
package main
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestHelloWorld(t *testing.T) {
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.Host != "foobar" {
t.Errorf("Host is %q, want foobar", r.Host)
}
})
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/api/login", nil)
r.Host = "foobar"
mux.ServeHTTP(w, r)
}
- 1 回答
- 0 關(guān)注
- 121 瀏覽
添加回答
舉報
0/150
提交
取消