Create http.Response instance with sample body string in golang
As suggested by Not_a_Golfer and JimB:
io.ReadCloser
is an interface that is satisfied when a struct
implements both the Read
and the Close
functions.
Fortunately, there is ioutil.NopCloser
, which takes a io.Reader
and wraps it in the nopCloser
struct, which implements both Read
and Close
. However, its Close
function does nothing as implied from the name.
Here is an example:
package main
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
)
func main() {
t := http.Response{
Body: ioutil.NopCloser(bytes.NewBufferString("Hello World")),
}
buff := bytes.NewBuffer(nil)
t.Write(buff)
fmt.Println(buff)
}
To play with the code, click here.
Further to the top answer, I have found that in order for the response to be treated as the genuine article by clients, it needs to be more fully formed. For a normal (200) response, I do the following:
body := "Hello world"
t := &http.Response{
Status: "200 OK",
StatusCode: 200,
Proto: "HTTP/1.1",
ProtoMajor: 1,
ProtoMinor: 1,
Body: ioutil.NopCloser(bytes.NewBufferString(body)),
ContentLength: int64(len(body)),
Request: req,
Header: make(http.Header, 0),
}
Then you can, for example, add headers (with a 401 status code, to ask for authorisation, say). req
is the http.Request
for which you are generating the response.