Created
August 20, 2016 18:01
-
-
Save codesword/2380f10f8ee4e1b1c1831fa5727dff17 to your computer and use it in GitHub Desktop.
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 ( | |
"io" | |
"net/http" | |
"os" | |
) | |
func main() { | |
server := http.Server{ | |
Addr: ":" + os.Getenv("PORT"), | |
Handler: &myHandler{}, | |
} | |
server.ListenAndServe() | |
} | |
func hello(w http.ResponseWriter, r *http.Request) { | |
io.WriteString(w, "Hello World!") | |
} | |
type myHandler struct{} | |
func (*myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
if r.URL.String() == "/hello" { | |
hello(w, r) | |
return | |
} | |
io.WriteString(w, "Route with URL: "+r.URL.String()) | |
} |
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 ( | |
"net/http" | |
"net/http/httptest" | |
"testing" | |
) | |
func processRequest(method, url string) (int, string) { | |
server := &myHandler{} | |
request, _ := http.NewRequest(method, url, nil) | |
recorder := httptest.NewRecorder() | |
server.ServeHTTP(recorder, request) | |
return recorder.Code, recorder.Body.String() | |
} | |
func TestHelloRoute(t *testing.T) { | |
status, body := processRequest("GET", "/hello") | |
if status != 200 { | |
t.Fatalf("Received non-200 response: %d\n", status) | |
} | |
expected := "Hello World!" | |
if expected != body { | |
t.Errorf("Expected the message '%s'\n", expected) | |
} | |
} | |
func TestOtherRoute(t *testing.T) { | |
status, body := processRequest("GET", "/") | |
if status != 200 { | |
t.Fatalf("Received non-200 response: %d\n", status) | |
} | |
expected := "Route with URL: /" | |
if expected != body { | |
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