gpt4 book ai didi

http - 如何在go中测试http请求

转载 作者:IT王子 更新时间:2023-10-29 02:36:15 29 4
gpt4 key购买 nike

我有一个 go 包,它基本上是 python API 的包装器。我不确定如何测试 http.NewRequest、client.Do 和 ioutil.ReadAll 的错误。我知道 httptest 存在,但我很新,我无法让它工作。任何帮助将不胜感激!

func DeleteApp(platform string, hostname string, header string) error {

if platform == "" || hostname == "" {
fmt.Printf("[DELETE APP] Platform and hostname can not be empty strings")
return errors.New("[DELETE APP] Platform and hostname can not be empty strings")
}
url := fmt.Sprintf(baseURL+"delete-app/%s/%s", platform, hostname)

// Create client & set timeout
client := &http.Client{}
client.Timeout = time.Second * 15

// Create request
req, err := http.NewRequest("DELETE", url, nil)
if err != nil {
fmt.Printf("[DELETE APP] Could not create request : %v", err)
return err
}

//check for optional header
if header != "" {
req.Header.Add("X-Fields", header)
}

// Fetch Request
resp, err := client.Do(req)
if err != nil {
fmt.Printf("[DELETE APP] Could not fetch request : %v", err)
return err
}
defer resp.Body.Close()

//Read Response Body
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Printf("[DELETE APP] Could not read response body : %v", err)
return err
}

fmt.Println("response Status : ", resp.Status)
fmt.Println("response Headers : ", resp.Header)
fmt.Println("response Body : ", string(respBody))

return nil

最佳答案

你可以使用httptest.NewServer

func TestDeleteApp(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello, client")
}))
defer ts.Close()

baseURL = ts.URL + "/"

DeleteApp("platform", "hostname", "header")

}

这会重写您的全局 baseURL,因此它不能是一个常量(您可能只想将其作为参数传递)。您可以在 http.HandlerFunc 或基于响应编写测试断言。

关于http - 如何在go中测试http请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52707948/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com