Skip to content

Instantly share code, notes, and snippets.

@var23rav
Last active July 4, 2019 08:59
Show Gist options
  • Save var23rav/13dc201f77565454da7acb53aa6721ad to your computer and use it in GitHub Desktop.
Save var23rav/13dc201f77565454da7acb53aa6721ad to your computer and use it in GitHub Desktop.
Goalang Http Test Server with routing features
package http_client
import (
"fmt"
"net/http"
"net/http/httptest"
log "github.com/sirupsen/logrus"
)
func getTestHTTPServer(expectedResponse string, resCode int) *httptest.Server {
return getHTTPServer(expectedResponse , resCode, false)
}
func getTestHTTPSServer(expectedResponse string, resCode int) *httptest.Server {
return getHTTPServer(expectedResponse , resCode, true)
}
// getHTTPServer create a test server for mocking response for any REST operation
func getHTTPServer(expectedResponse string, resCode int, enableHtts bool) *httptest.Server {
handlerFunc := http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
res.WriteHeader(resCode)
_, err := res.Write([]byte(expectedResponse))
if err != nil {
log.WithFields(log.Fields{
"Response": expectedResponse,
}).Error("TestHTTPServer failed to write response.")
}
})
if enableHtts {
testSecureServer := httptest.NewTLSServer(handlerFunc)
return testSecureServer
}
testServer := httptest.NewServer(handlerFunc)
return testServer
}
type TestHTTPServerURLConf struct {
URLPath string
Method string
Result string
Code int
}
func getTestHTTPServerWithURLPath(urlPathConfList []TestHTTPServerURLConf) *httptest.Server {
return getHTTPServerWithURLPath(urlPathConfList, false)
}
func getTestHTTPSServerWithURLPath(urlPathConfList []TestHTTPServerURLConf) *httptest.Server {
return getHTTPServerWithURLPath(urlPathConfList, true)
}
// getHTTPServerWithURLPath create a test server for mocking response by URL Path config
func getHTTPServerWithURLPath(urlPathConfList []TestHTTPServerURLConf, enableHtts bool) *httptest.Server {
handlerFunc := http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
var matchedURLPathConf TestHTTPServerURLConf
var doesReqURLMatched, doesReqMethodMatched bool
for _, urlPathConf := range urlPathConfList {
if (urlPathConf.URLPath == req.URL.Path) {
doesReqURLMatched = true
if(urlPathConf.Method == "" || urlPathConf.Method == req.Method) {
doesReqMethodMatched = true
matchedURLPathConf = urlPathConf
break
}
}
}
if !doesReqURLMatched {
matchedURLPathConf.Result = fmt.Sprintf("Path Not Found for requested URL '%s' !", req.URL.Path)
matchedURLPathConf.Code = 404
} else if !doesReqMethodMatched {
matchedURLPathConf.Result = fmt.Sprintf("Method '%s' Not Allowed for requested URL Path '%s'!", req.Method, req.URL.Path)
matchedURLPathConf.Code = 405
}
if matchedURLPathConf.Code == 0 {
matchedURLPathConf.Code = 200
}
res.WriteHeader(matchedURLPathConf.Code)
_, err := res.Write([]byte(matchedURLPathConf.Result))
if err != nil {
log.WithFields(log.Fields{
"Response": matchedURLPathConf.Result,
}).Error("TestHTTPServer failed to write response.")
}
})
if enableHtts {
testSecureServer := httptest.NewTLSServer(handlerFunc)
return testSecureServer
}
testServer := httptest.NewServer(handlerFunc)
return testServer
}
package http_client
import (
"http"
"io/ioutil"
"testing"
)
func TestCreateAPDataSuccess(t *testing.T) {
testResList := []TestHTTPServerURLConf {
{
URLPath: "/login/token",
Method: "POST",
Result: `{
"access_token": "valid token"
}`,
Code: 200,
},
{
URLPath: "/api/v2/user/",
Method: "GET",
Result: "{}",
Code: 200,
},
}
testServer := getTestHTTPSServerWithURLPath(testResList)
resp, err := http.Get(testServer.URL)
if err != nil {
// handle error
}
defer resp.Body.Close()
contents, err := ioutil.ReadAll(resp.Body)
if err != nil {
// handle error
}
fmt.Printf("%s\n", string(contents))
}
  • Golang Simple HTTP Server

    • getHTTPServer Base function Allows you to create a simple Http test server. It accepts response as a string and response code as int.

    • You can get the URL of test server from getTestHTTPServerWithURLPath

    • For HTTP use getTestHTTPServer and for HTTPS use getTestHTTPSServer. Both are wrapper over getTestHTTPServerWithURLPath.

    • You will be able to get test server url using getTestHTTPServer(`{'result':'test result'}`, 200) for Http server and getTestHTTPSServer(`{'result':'test result'}`, 200) for Https server.

  • Golang Test HTTP Server with Routing capability

    • getTestHTTPServerWithURLPath Allows you to create an Http test server with Routing Capability.

    • You can get the url of test server from getTestHTTPServerWithURLPath

    • For HTTP use getTestHTTPServerWithURLPath and for HTTPS use getTestHTTPSServerWithURLPath. Both are wrapper over getTestHTTPServerWithURLPath.

    • TestHTTPServerURLConf struct help you to create the routing configuration. Example

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment