Create an http.Response instance with a model body string in golang

I am ready to create a http.Response sample in golang with a sample string.

The problem is that its body property accepts an instance of ReadCloser . But, as its instance of a fictitious answer, I was wondering if there was any trick to easily install it without setting up all the read / close parts of the stream.

+8
go response
source share
3 answers

As suggested by Not_a_Golfer and JimB :

io.ReadCloser is an interface that is executed when a struct implements Read and Close functions.

Fortunately, there is an ioutil.NopCloser that accepts io.Reader and transfers it to the nopCloser structure, which implements both Read and Close . However, its Close function does nothing as the name implies.

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 .

+16
source

In addition to the top answer, I found that in order for an answer to be perceived as a genuine customer article, it needs to be more fully formed. For a normal (200) answer, 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 status code 401 to ask for authorization, say). req is the http.Request for which you are generating a response.

+4
source

That should work.

 func main(){ go serveHTTP(*port, *host) select {} } func serveHTTP(port int, host string) { mux := http.NewServeMux() mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { requestHandler(w, r) }) addr := fmt.Sprintf("%v:%d", host, port) server := &http.Server { Addr: addr, Handler: mux, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, MaxHeaderBytes: 1 << 20, } err := server.ListenAndServe() log.Println(err.Error()) } func requestHandler(w http.ResponseWriter, r *http.Request){ fmt.Fprintf(w, `Success!`) } 
+1
source

All Articles