Skip to content

Instantly share code, notes, and snippets.

@paddycarver
Created October 17, 2014 02:40
Show Gist options
  • Save paddycarver/88130fc57a2fd82c7947 to your computer and use it in GitHub Desktop.
Save paddycarver/88130fc57a2fd82c7947 to your computer and use it in GitHub Desktop.
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"]))
}
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