HTTP server vs client request in golang

huangapple go评论82阅读模式
英文:

HTTP server vs client request in golang

问题

根据文档,服务器和客户端的HTTP请求之间存在差异,例如在请求体为空的情况下。我该如何创建一个服务器请求来模拟传入的HTTP请求以进行测试?

编辑:我特别想创建一个用于单元测试的HTTP服务器请求。

英文:

The documentation says there's a difference between server and client http request, for example, in the case where the body is empty. How do I create a server request to simulate incoming http request for testing purpose?

Edit: I specifically want to create http server request for use during unit test.

答案1

得分: 2

抱歉回答晚了。昨晚有点分心。这是一个使用非空body创建请求对象的快速示例。需要注意的一点是,我认为我没有问过的是,HTTP GET请求没有body,所以你可能始终会得到一个nil值。对此我不能确定,但如果是这样的话,我也不会感到惊讶。

package main

import "fmt"
import "net/http"
import "strings"

func main() {
        reader := strings.NewReader("")
        req, _ := http.NewRequest("POST", "http://example.com", reader)
	fmt.Printf("Body != nil ? %v, value: %s END\n", req.Body != nil, req.Body)
}

链接:https://play.golang.org/p/5Fb6b2qgSo

英文:

Sorry for the delayed answer. Got a bit side tracked last night. Here's a quick example of making a request object with a non-nil body. One thing to note that I don't think I bothered asking, HTTP GET's don't have a body so you may always get a nil value for that HTTP method. Not positive about that but it would not surprise me if it were the case.

package main

import "fmt"
import "net/http"
import "strings"

func main() {
        reader := strings.NewReader("")
        req, _ := http.NewRequest("POST", "http://example.com", reader)
	fmt.Printf("Body != nil ? %v, value: %s END\n", req.Body != nil, req.Body)
}

https://play.golang.org/p/5Fb6b2qgSo

答案2

得分: 1

我不知道你是否还在这里寻找答案,但是Go实际上有一个用于测试HTTP服务器的包。

https://golang.org/pkg/net/http/httptest/

这个包非常适合测试。你可以通过它来创建请求和服务器进行测试。

英文:

I dont know if you are still looking for an answer here, but Go actually has a package for testing HTTP servers.

https://golang.org/pkg/net/http/httptest/

Its fantastic for testing. You can create both the request and the server through here for testing.

huangapple
  • 本文由 发表于 2015年10月21日 06:44:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/33248090.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定