go http testing code example
Example: go http testing
package helper
import (
"bytes"
"encoding/binary"
"net/http"
"net/http/httptest"
"github.com/sirupsen/logrus"
)
func HttpTestRequest(handler http.Handler, method, url string, payload []byte) *httptest.ResponseRecorder {
request := make(chan *http.Request)
errors := make(chan error)
if binary.Size(payload) > 0 {
req, err := http.NewRequest(method, url, bytes.NewBuffer(payload))
go func() {
request <- req
errors <- err
}()
} else {
req, err := http.NewRequest(method, url, nil)
go func() {
request <- req
errors <- err
}()
}
if <-errors != nil {
logrus.Error(<-errors)
}
rr := httptest.NewRecorder()
handler.ServeHTTP(rr, <-request)
return rr
}