go http custom test code example
Example: go custom http request testing
package main
import (
"bytes"
"encoding/binary"
"net/http"
"net/http/httptest"
"github.com/sirupsen/logrus"
)
func JSONStrigify(payload string) []byte {
jsonData := []byte(payload)
return jsonData
}
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
}
func TestCreateAccount(t *testing.T) {
router := setupRouter()
res := helper.HttpTestRequest(router, "POST", "/account", helper.JSONStrigify(`{
"name":"xyz",
"ic_type":"pqr",
"ic_number_identity":"[email protected]",
"account_number":"1234567890",
"account_name":"1234567890",
"bank_name":"1234567890",
"type":"1234567890"
}`))
assert.Equal(t, http.StatusOK, res.Code)
}