Testing the HTTP handler
The testing of the HTTP
server could be complicated. The Go standard library simplifies this with a handy package, net/http/httptest
. This recipe describes how to utilize this package to test the HTTP
handlers.
How to do it...
- Open the console and create the folder
chapter11/recipe05
. - Navigate to the directory.
- Create the file
sample_test.go
with the following content:
package main import ( "fmt" "io/ioutil" "net/http" "net/http/httptest" "testing" "time" ) const cookieName = "X-Cookie" func HandlerUnderTest(w http.ResponseWriter, r *http.Request) { http.SetCookie(w, &http.Cookie{ Domain: "localhost", Expires: time.Now().Add(3 * time.Hour), Name: cookieName, }) r.ParseForm() username := r.FormValue("username") fmt.Fprintf(w, "Hello %s!", username) } func TestHttpRequest...