Skip to content

Instantly share code, notes, and snippets.

@danfoust
Last active November 22, 2020 15:11
Show Gist options
  • Save danfoust/e12f6194fd9a3e7a9c230e48cf52753a to your computer and use it in GitHub Desktop.
Save danfoust/e12f6194fd9a3e7a9c230e48cf52753a to your computer and use it in GitHub Desktop.
Simple Go HTTP Test
package main
import (
"fmt"
"net/http"
)
func IndexHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Hello World")
}
func main() {
http.HandleFunc("/", IndexHandler)
http.ListenAndServe(":80", nil)
}
package main
import (
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
)
func TestIndexHandler(t *testing.T) {
w := httptest.NewRecorder()
r := httptest.NewRequest(http.MethodGet, "/", nil)
IndexHandler(w, r)
resp := w.Result()
body, _ := ioutil.ReadAll(resp.Body)
//fmt.Println(resp.StatusCode)
//fmt.Println(resp.Header.Get("Content-Type"))
//fmt.Println(string(body))
got := string(body)
want := "Hello World"
if got != want {
t.Errorf("got %q, wanted %q", got, want)
}
if resp.StatusCode != 200 {
t.Errorf("Status was not 200, got %q instead", resp.StatusCode)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment