Skip to content

Instantly share code, notes, and snippets.

@karampok
Created April 10, 2019 20:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karampok/6d240dfa3b5906d47167f2fb09bd8ca0 to your computer and use it in GitHub Desktop.
Save karampok/6d240dfa3b5906d47167f2fb09bd8ca0 to your computer and use it in GitHub Desktop.
package main
import (
"context"
"log"
"net/http"
"os"
"os/signal"
"time"
)
type server struct {
rtr *http.ServeMux
}
func newServer() *server {
s := &server{rtr: http.NewServeMux()}
s.routes()
return s
}
func (s *server) routes() {
s.rtr.HandleFunc("/about", s.handleAbout())
s.rtr.HandleFunc("/", s.handleIndex())
s.rtr.HandleFunc("/admin", s.adminOnly(s.handleAdminIndex()))
}
func (s *server) handleAbout() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("about me\n"))
}
}
func (s *server) handleIndex() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("main index\n"))
}
}
func (s *server) handleAdminIndex() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("admin only\n"))
}
}
func (s *server) adminOnly(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if true { //!currentUser(r).IsAdmin {
http.NotFound(w, r)
return
}
h(w, r)
}
}
func (s server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("server", ".me")
s.rtr.ServeHTTP(w, r)
}
func main() {
h := &http.Server{Addr: ":8080", Handler: newServer()}
lg := log.New(os.Stdout, "", 0)
go func() {
lg.Println("Listening :8080")
if err := h.ListenAndServe(); err != nil {
lg.Fatal(err)
}
}()
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt)
<-stop
lg.Println("Shutting down the server ...")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := h.Shutdown(ctx); err != nil {
lg.Fatal(err)
}
lg.Printf("Server stopped gracefully ...")
}
@karampok
Copy link
Author

func TestHandleAbout(t *testing.T) {
	is := is.New(t)
	srv := server{
		db:    mockDatabase,
		email: mockEmailSender,
	}
	srv.routes()
	req, err := http.NewRequest("GET", "/about", nil)
	is.NoErr(err)
	w := httptest.NewRecorder()
	srv.ServeHTTP(w, req)
	is.Equal(w.StatusCode, http.StatusOK)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment