diff --git a/articles.go b/articles.go index edada5f..5e165ce 100644 --- a/articles.go +++ b/articles.go @@ -2,6 +2,7 @@ package main import ( "encoding/json" + "log" "net/http" ) @@ -22,6 +23,7 @@ func getAllArticles() http.Handler { } json.NewEncoder(w).Encode(articles) + log.Println("Served /articles") } return http.HandlerFunc(fn) diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..417f06d --- /dev/null +++ b/go.mod @@ -0,0 +1,5 @@ +module go-rest-api + +go 1.13 + +require github.com/gorilla/mux v1.8.0 diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..5350288 --- /dev/null +++ b/go.sum @@ -0,0 +1,2 @@ +github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI= +github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= diff --git a/main.go b/main.go index b789894..e6c1944 100644 --- a/main.go +++ b/main.go @@ -1,14 +1,32 @@ package main import ( + "context" "fmt" + "log" + "os" + "os/signal" + "time" ) func main() { fmt.Println("Hello world!") s := Server{ - port: ":3000", + port: ":9999", } - s.serve() + + go func() { + s.serve() + }() + + signCh := make(chan os.Signal) + signal.Notify(signCh, os.Interrupt) + signal.Notify(signCh, os.Kill) + + sig := <-signCh + log.Println("Received terminal, graceful shutdown", sig) + + tc, _ := context.WithTimeout(context.Background(), 30*time.Second) + s.shutdown(tc) } diff --git a/server.go b/server.go index 47cebaf..331209b 100644 --- a/server.go +++ b/server.go @@ -1,22 +1,39 @@ package main import ( + "context" "log" "net/http" + "time" + + "github.com/gorilla/mux" ) // Server base struct type Server struct { - port string + port string + server http.Server } func (s *Server) serve() { - mux := http.NewServeMux() - mux.Handle("/", s.handle()) - mux.Handle("/articles", getAllArticles()) + sm := mux.NewRouter() + sm.Handle("/", s.handle()) + sm.Handle("/articles", getAllArticles()) + serv := &http.Server{ + Addr: s.port, + Handler: sm, + IdleTimeout: 120 * time.Second, + ReadTimeout: 1 * time.Second, + WriteTimeout: 1 * time.Second, + } + s.server = *serv log.Print("Listening on", s.port) - log.Fatal(http.ListenAndServe(s.port, mux)) + + err := serv.ListenAndServe() + if err != nil { + log.Fatal(err) + } } func (s *Server) handle() http.Handler { @@ -26,3 +43,7 @@ func (s *Server) handle() http.Handler { return http.HandlerFunc(fn) } + +func (s *Server) shutdown(tc context.Context) { + s.server.Shutdown(tc) +}