登录
首页 >  Golang >  Go问答

如何使用Go的httptest模拟多个不同的HTTP响应?

来源:stackoverflow

时间:2024-03-17 13:30:29 103浏览 收藏

在 Go 语言中使用 httptest 模拟 HTTP 响应时,开发者可能需要模拟不同的响应内容。通过在 handlerResponse 函数中使用一个自定义的 responseWriter 结构,可以实现这一目的。这个结构包含一个映射表,其中键为请求次数,值为不同的响应内容。在处理程序函数中,每次收到请求时,responseWriter 会根据请求次数返回相应的响应内容。这样,在进行多次 HTTP 请求时,模拟的服务器可以提供不同的响应数据,满足测试用例的需求。

问题内容

我创建了一些 go 函数,这些函数可以对互联网上的服务进行 http get 调用并解析结果。

我现在正在为这些功能编写测试用例。 在我的测试用例中,我使用 go 包 httptest 来模拟对这些外部服务的调用。下面是我的代码。为了简洁起见,特意删除了错误检查。这是演示。

package main

import (
    "fmt"
    "io"
    "context"
    "net/http"
    "net/http/httptest"
)

func handlerresponse() http.handler {
    return http.handlerfunc(func(w http.responsewriter, r *http.request) {
        w.writeheader(http.statusok)
        w.write([]byte(`{"a":"b"}`))
    })
}

func buildmyrequest(ctx context.context, url string) *http.request {
    request, _ := http.newrequestwithcontext(ctx, "get", url, nil)
    return request
}

func myprint(response *http.response) {
    b := make([]byte, 60000)
    for {
        _, err := response.body.read(b)
        if err == io.eof {
            break
        }
    }
    fmt.println(string(b))
}

func main() {
    srv := httptest.newserver(handlerresponse())            
    client := http.client{}

    myresponse1, _ := client.do(buildmyrequest(context.background(), srv.url))
    fmt.println("myresponse1:")
    myprint(myresponse1)
    
    myresponse2, _ := client.do(buildmyrequest(context.background(), srv.url))
    fmt.println("myresponse2:")
    myprint(myresponse2)

}

这是它产生的输出:

myResponse1:
{"A":"B"}
myResponse2:
{"A":"B"}

如您所见,我创建了一些虚拟 http 响应数据 {"a":"b"},当您向 srv.url 发送 http 请求时,它实际上会命中一个临时 http 服务器,该服务器以虚拟数据。酷!

当您向 srv.url 发送第二个 http 请求时,它再次使用相同的虚拟数据进行响应。但这就是我的问题出现的地方。我希望临时 http 服务器在第二次 {"c":"d"} 和第三次 {"e":"f"} 收到请求时返回一些不同的数据。

如何更改 main() 函数的第一行,以便服务器在后续 http 调用中响应我所需的数据?


正确答案


你可以使用如下的 hack(演示:here

package main

import (
    "fmt"
    "io"
    "context"
    "net/http"
    "net/http/httptest"
    "sync"
)


type responseWriter struct{
   resp map[int]string
   count int
   lock *sync.Mutex
}

func NewResponseWriter()*responseWriter{
   r := new(responseWriter)
   r.lock = new(sync.Mutex)
   r.resp = map[int]string{
    0: `{"E":"F"}`,
    1: `{"A":"B"}`,
    2: `{"C":"D"}`,
   }
   r.count = 0
   return r
}

func (r *responseWriter)GetResp()string{
   r.lock.Lock()
   defer r.lock.Unlock()
   r.count ++
   return r.resp[r.count%3]
}


func handlerResponse(rr *responseWriter) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(http.StatusOK)
        w.Write([]byte(rr.GetResp()))
    })
}

func buildMyRequest(ctx context.Context, url string) *http.Request {
    request, _ := http.NewRequestWithContext(ctx, "GET", url, nil)
    return request
}


func myPrint(response *http.Response) {
    b := make([]byte, 60000)
    for {
        _, err := response.Body.Read(b)
        if err == io.EOF {
            break
        }
    }
    fmt.Println(string(b))
}

func main() {
        rr := NewResponseWriter()

    srv := httptest.NewServer(handlerResponse(rr))  
    client := http.Client{}

    myResponse1, err := client.Do(buildMyRequest(context.Background(), srv.URL))
    if err != nil{
       fmt.Println(err)
       return
    }
    
    defer myResponse1.Body.Close()
    fmt.Println("myResponse1:")
    myPrint(myResponse1)
    
    myResponse2, err := client.Do(buildMyRequest(context.Background(), srv.URL))
    if err != nil{
       fmt.Println(err)
       return
    }
    
    defer myResponse2.Body.Close()
    fmt.Println("myResponse2:")
    myPrint(myResponse2)
}

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>