Running tool: /usr/local/go/bin/go test -timeout 30s -run ^(ExampleBuild)$--- FAIL: ExampleBuild (0.00s)got:POST localhost/status?t=1 HTTP/1.1Content-Type: application/jsonwant:POST localhost/status?t=1 HTTP/1.1Content-Type: application/jsonFAILexit status 1我正在嘗試使用 Example 方法編寫測試。我創建了一個帶有標頭(Content-Type:application/json)、查詢參數 t=1、方法類型 POST 和 URL localhost 的 http 請求。got: 和 want: 中的輸出看起來是一樣的,還檢查了空白字符。無法弄清楚這兩者之間有什么區別。無法弄清楚我在這里錯過了什么。import ( "fmt" "net/http" "net/http/httputil")func ExampleBuild() { req, err := http.NewRequest(http.MethodPost, "localhost/status?t=1", nil) req.Header.Add("content-type", "application/json") if err != nil { panic(err) } str, err := httputil.DumpRequest(req, false) if err != nil { panic(err) } fmt.Printf("%s", string(str)) // Output: // POST localhost/status?t=1 HTTP/1.1 // Content-Type: application/json}
1 回答

胡說叔叔
TA貢獻1804條經驗 獲得超8個贊
我認為正在發生的事情是 HTTP 標頭的\r\n
?換行符。所以這就是httputil.DumpRequest
回報。但是您可能正在一臺不使用\r\n
換行符的機器上編輯這個文件,所以區別就在于此。
成功比較的蠻力方法是:
fmt.Println(strings.Replace(string(str),?"\r",?"",?-1))
它從 HTTP 轉儲的字符串中刪除了“\r”,如果您的編輯器僅使用“\n”來破壞預期輸出,它將成功進行比較。
更優雅的解決方案將取決于您的測試環境的細節。
- 1 回答
- 0 關注
- 179 瀏覽
添加回答
舉報
0/150
提交
取消