Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create http.Response instance with sample body string in golang

Tags:

http

go

response

I am willing to create a sample http.Response instance in golang with a sample body string.

Problem is, its body property accepts ReadCloser instance. But as its a dummy response instance, I was wondering if there is some trick to set it easily without setting up all that stream read/close parts.

like image 911
Rana Avatar asked Nov 29 '15 00:11

Rana


1 Answers

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.

like image 133
boaz_shuster Avatar answered Sep 19 '22 14:09

boaz_shuster