-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
112 lines (85 loc) · 3.22 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package main
import (
"context"
"log"
"net/http"
"os"
"os/signal"
"time"
"github.com/go-openapi/runtime/middleware"
gohandlers "github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/hashicorp/go-hclog"
"github.com/nicholasjackson/env"
"google.golang.org/grpc"
protos "github.com/piyush1146115/go-microservice/currency/protos/currency"
"github.com/piyush1146115/go-microservice/product-api/data"
"github.com/piyush1146115/go-microservice/product-api/handlers"
)
var bindAddress = env.String("BIND_ADDRESS", false, ":9090", "Bind address for the server")
func main() {
env.Parse()
l := hclog.Default()
v := data.NewValidation()
conn, err := grpc.Dial("localhost:9092", grpc.WithInsecure())
if err != nil {
panic(err)
}
defer conn.Close()
// create client
cc := protos.NewCurrencyClient(conn)
// create a database instance
db := data.NewProductDB(cc, l)
// create the handlers
ph := handlers.NewProducts(l, v, db)
// create a new serve mux and register the handlers
sm := mux.NewRouter()
// handlers for API
getR := sm.Methods(http.MethodGet).Subrouter()
getR.HandleFunc("/products", ph.ListAll).Queries("currency", "{[A-Z]{3}}")
getR.HandleFunc("/products", ph.ListAll)
getR.HandleFunc("/products/{id:[0-9]+}", ph.ListSingle).Queries("currency", "{[A-Z]{3}}")
getR.HandleFunc("/products/{id:[0-9]+}", ph.ListSingle)
putR := sm.Methods(http.MethodPut).Subrouter()
putR.HandleFunc("/products", ph.Update)
putR.Use(ph.MiddlewareValidateProduct)
postR := sm.Methods(http.MethodPost).Subrouter()
postR.HandleFunc("/products", ph.Create)
postR.Use(ph.MiddlewareValidateProduct)
deleteR := sm.Methods(http.MethodDelete).Subrouter()
deleteR.HandleFunc("/products/{id:[0-9]+}", ph.Delete)
opts := middleware.RedocOpts{SpecURL: "/swagger.yaml"}
sh := middleware.Redoc(opts, nil)
getR.Handle("/docs", sh)
getR.Handle("/swagger.yaml", http.FileServer(http.Dir("./")))
// CORS
ch := gohandlers.CORS(gohandlers.AllowedOrigins([]string{"*"}))
// create a new server
s := http.Server{
Addr: *bindAddress, // configure the bind address
Handler: ch(sm), // set the default handler
ErrorLog: l.StandardLogger(&hclog.StandardLoggerOptions{}), // set the logger for the server
ReadTimeout: 5 * time.Second, // max time to read request from the client
WriteTimeout: 10 * time.Second, // max time to write response to the client
IdleTimeout: 120 * time.Second, // max time for connections using TCP Keep-Alive
}
// start the server
go func() {
l.Info("Starting server on port 9090")
err := s.ListenAndServe()
if err != nil {
l.Error("Error starting server", "error", err)
os.Exit(1)
}
}()
// trap sigterm or interupt and gracefully shutdown the server
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
signal.Notify(c, os.Kill)
// Block until a signal is received.
sig := <-c
log.Println("Got signal:", sig)
// gracefully shutdown the server, waiting max 30 seconds for current operations to complete
ctx, _ := context.WithTimeout(context.Background(), 30*time.Second)
s.Shutdown(ctx)
}