Created
October 17, 2014 02:40
-
-
Save paddycarver/88130fc57a2fd82c7947 to your computer and use it in GitHub Desktop.
This file contains 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" | |
"github.com/gorilla/mux" | |
) | |
func main() { | |
http.Handle("/", getRouter()) | |
} | |
func getRouter() *mux.Router { | |
r := mux.NewRouter() | |
r.HandleFunc("/{name}", NameHandler) | |
return r | |
} | |
func NameHandler(w http.ResponseWriter, r *http.Request) { | |
vars := mux.Vars(r) | |
w.Write([]byte("Hello, " + vars["name"])) | |
} |
This file contains 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 TestNameHandler(t *testing.T) { | |
r := getRouter() | |
req, err := http.NewRequest("GET", "https://example.com/Paddy", nil) | |
if err != nil { | |
t.Fatal("Can't build request:", err) | |
} | |
w := httptest.NewRecorder() | |
r.ServeHTTP(w, req) | |
if w.Code != http.StatusOK { | |
t.Errorf("Expected response code to be %d, got %d", http.StatusOK, w.Code) | |
} | |
if w.Body.String() != "Hello, Paddy" { | |
t.Errorf(`Expected response to be "%s", got "%s"`, "Hello, Paddy", w.Body.String()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment