This repository has been archived by the owner on Oct 5, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
75 lines (61 loc) · 1.67 KB
/
server.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
package cmd
import (
"context"
"net/http"
"os"
"os/signal"
"time"
"github.com/dotkom/image-server/internal/api"
bigcache_adapter "github.com/dotkom/image-server/internal/cache/bigcache"
gorm_adapter "github.com/dotkom/image-server/internal/storage/gorm"
s3_adapter "github.com/dotkom/image-server/internal/storage/s3"
"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var serverCmd = &cobra.Command{
Use: "server",
Short: "Start the server",
Long: `Start the server`,
Run: func(cmd *cobra.Command, args []string) {
serve()
},
}
func serve() {
fs, err := s3_adapter.New(viper.GetString(s3Bucket))
if err != nil {
log.Fatal("Failed to create storage adapter", err)
}
ms := gorm_adapter.New(gorm_adapter.DBDriver(viper.GetString(dbDriver)), viper.GetString(dbDSN))
ms.Migrate()
cache, err := bigcache_adapter.New()
if err != nil {
log.Fatal("Failed to create cache adapter", err)
}
router := mux.NewRouter()
api := api.New(fs, ms, cache, router)
defer api.Close()
server := &http.Server{
Addr: viper.GetString(listenAddr),
WriteTimeout: time.Second * 30,
ReadTimeout: time.Second * 30,
IdleTimeout: time.Second * 60,
Handler: api,
}
go func() {
log.Infof("Server listening to %s", viper.GetString(listenAddr))
if err := server.ListenAndServe(); err != nil {
log.Error(err)
}
}()
channel := make(chan os.Signal, 1)
signal.Notify(channel, os.Interrupt)
sig := <-channel
log.Infof("Recieved signal: %s", sig)
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
server.Shutdown(ctx)
log.Info("Shutting down")
os.Exit(0)
}