Answers for "go http testing"

Go
0

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
}
Posted by: Guest on April-01-2021

Browse Popular Code Answers by Language