forked from nicholasjackson/building-microservices-youtube
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
99 lines (80 loc) · 2.89 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
package main
import (
"context"
"net/http"
"os"
"os/signal"
"time"
gohandlers "github.com/gorilla/handlers"
"github.com/gorilla/mux"
hclog "github.com/hashicorp/go-hclog"
"github.com/nicholasjackson/building-microservices-youtube/product-images/files"
"github.com/nicholasjackson/building-microservices-youtube/product-images/handlers"
"github.com/nicholasjackson/env"
)
var bindAddress = env.String("BIND_ADDRESS", false, ":9091", "Bind address for the server")
var logLevel = env.String("LOG_LEVEL", false, "debug", "Log output level for the server [debug, info, trace]")
var basePath = env.String("BASE_PATH", false, "./imagestore", "Base path to save images")
func main() {
env.Parse()
l := hclog.New(
&hclog.LoggerOptions{
Name: "product-images",
Level: hclog.LevelFromString(*logLevel),
},
)
// create a logger for the server from the default logger
sl := l.StandardLogger(&hclog.StandardLoggerOptions{InferLevels: true})
// create the storage class, use local storage
// max filesize 5MB
stor, err := files.NewLocal(*basePath, 1024*1000*5)
if err != nil {
l.Error("Unable to create storage", "error", err)
os.Exit(1)
}
// create the handlers
fh := handlers.NewFiles(stor, l)
mw := handlers.GzipHandler{}
// create a new serve mux and register the handlers
sm := mux.NewRouter()
ch := gohandlers.CORS(gohandlers.AllowedOrigins([]string{"*"}))
// upload files
ph := sm.Methods(http.MethodPost).Subrouter()
ph.HandleFunc("/images/{id:[0-9]+}/{filename:[a-zA-Z]+\\.[a-z]{3}}", fh.UploadREST)
ph.HandleFunc("/", fh.UploadMultipart)
// get files
gh := sm.Methods(http.MethodGet).Subrouter()
gh.Handle(
"/images/{id:[0-9]+}/{filename:[a-zA-Z]+\\.[a-z]{3}}",
http.StripPrefix("/images/", http.FileServer(http.Dir(*basePath))),
)
gh.Use(mw.GzipMiddleware)
// create a new server
s := http.Server{
Addr: *bindAddress, // configure the bind address
Handler: ch(sm), // set the default handler
ErrorLog: sl, // 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", "bind_address", *bindAddress)
err := s.ListenAndServe()
if err != nil {
l.Error("Unable to start 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
l.Info("Shutting down server with", "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)
}