Added Gorilla/mux library

This commit is contained in:
Piotr Biernat 2020-09-17 18:01:18 +02:00
parent b62a2bc863
commit ed9d44f8bf
5 changed files with 55 additions and 7 deletions

View File

@ -2,6 +2,7 @@ package main
import ( import (
"encoding/json" "encoding/json"
"log"
"net/http" "net/http"
) )
@ -22,6 +23,7 @@ func getAllArticles() http.Handler {
} }
json.NewEncoder(w).Encode(articles) json.NewEncoder(w).Encode(articles)
log.Println("Served /articles")
} }
return http.HandlerFunc(fn) return http.HandlerFunc(fn)

5
go.mod Normal file
View File

@ -0,0 +1,5 @@
module go-rest-api
go 1.13
require github.com/gorilla/mux v1.8.0

2
go.sum Normal file
View File

@ -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=

22
main.go
View File

@ -1,14 +1,32 @@
package main package main
import ( import (
"context"
"fmt" "fmt"
"log"
"os"
"os/signal"
"time"
) )
func main() { func main() {
fmt.Println("Hello world!") fmt.Println("Hello world!")
s := Server{ 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)
} }

View File

@ -1,22 +1,39 @@
package main package main
import ( import (
"context"
"log" "log"
"net/http" "net/http"
"time"
"github.com/gorilla/mux"
) )
// Server base struct // Server base struct
type Server struct { type Server struct {
port string port string
server http.Server
} }
func (s *Server) serve() { func (s *Server) serve() {
mux := http.NewServeMux() sm := mux.NewRouter()
mux.Handle("/", s.handle()) sm.Handle("/", s.handle())
mux.Handle("/articles", getAllArticles()) 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.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 { func (s *Server) handle() http.Handler {
@ -26,3 +43,7 @@ func (s *Server) handle() http.Handler {
return http.HandlerFunc(fn) return http.HandlerFunc(fn)
} }
func (s *Server) shutdown(tc context.Context) {
s.server.Shutdown(tc)
}