Added Gorilla/mux library
This commit is contained in:
parent
b62a2bc863
commit
ed9d44f8bf
@ -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)
|
||||
|
5
go.mod
Normal file
5
go.mod
Normal 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
2
go.sum
Normal 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=
|
20
main.go
20
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",
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
29
server.go
29
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
|
||||
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)
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user