-
-
Save vuon9/f9012b3752fe13cd469931873b4ef0c0 to your computer and use it in GitHub Desktop.
Example of testing Go HTTP servers using httptest.Server.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"log" | |
"myserver" | |
"net/http" | |
) | |
const addr = "localhost:12345" | |
func main() { | |
mux := http.NewServeMux() | |
handler := &myserver.MyHandler{} | |
mux.Handle("/favicon.ico", http.NotFoundHandler()) | |
mux.Handle("/", handler) | |
log.Printf("Now listening on %s...\n", addr) | |
server := http.Server{Handler: mux, Addr: addr} | |
log.Fatal(server.ListenAndServe()) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package myserver | |
import ( | |
"fmt" | |
"net/http" | |
"sync" | |
) | |
type MyHandler struct { | |
sync.Mutex | |
count int | |
} | |
func (h *MyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
var count int | |
h.Lock() | |
h.count++ | |
count = h.count | |
h.Unlock() | |
fmt.Fprintf(w, "Visitor count: %d.", count) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package myserver | |
import ( | |
"fmt" | |
"io/ioutil" | |
"net/http" | |
"net/http/httptest" | |
"testing" | |
) | |
func TestMyHandler(t *testing.T) { | |
handler := &MyHandler{} | |
server := httptest.NewServer(handler) | |
defer server.Close() | |
for _, i := range []int{1, 2} { | |
resp, err := http.Get(server.URL) | |
if err != nil { | |
t.Fatal(err) | |
} | |
if resp.StatusCode != 200 { | |
t.Fatalf("Received non-200 response: %d\n", resp.StatusCode) | |
} | |
expected := fmt.Sprintf("Visitor count: %d.", i) | |
actual, err := ioutil.ReadAll(resp.Body) | |
if err != nil { | |
t.Fatal(err) | |
} | |
if expected != string(actual) { | |
t.Errorf("Expected the message '%s'\n", expected) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment