Skip to content

Instantly share code, notes, and snippets.

@Integralist
Created May 22, 2016 14:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Integralist/cf76668bc46d75058ab5f566d96ce74a to your computer and use it in GitHub Desktop.
Save Integralist/cf76668bc46d75058ab5f566d96ce74a to your computer and use it in GitHub Desktop.
// package main is used here just for ease of running the demo.
// In reality, this would be package app
package main
import (
"flag"
"fmt"
"log"
"net/http"
)
// App is our Application's base http.Handler
type App struct {
*http.ServeMux
}
// NewApp constructs a new App and initializes our routing
func NewApp() *App {
mux := http.NewServeMux()
app := &App{mux}
mux.HandleFunc("/", app.Root)
return app
}
// Root is the root page of our application
func (a *App) Root(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Hello!")
}
var port = flag.Int("port", 8080, "Port to serve on")
func main() {
flag.Parse()
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", *port), NewApp()))
}
func TestAppRoot(t *testing.T) {
app := NewApp()
server := httptest.NewServer(app)
defer server.Close()
resp, err := http.Get(server.URL + "/")
if err != nil {
t.Error(err)
}
buf := &bytes.Buffer{}
buf.ReadFrom(resp.Body)
if strings.Index(buf.String(), "Hello!") == -1 {
t.Error("Root should say hello")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment