Created
April 10, 2019 20:17
-
-
Save karampok/6d240dfa3b5906d47167f2fb09bd8ca0 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 ( | |
"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 ...") | |
} |
Author
karampok
commented
Apr 10, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment