blob: 6b079144f5c55bd86869aad416dcdd2b807fae7b [file] [log] [blame]
iomodob892d072021-02-22 00:23:16 +04001package server
2
3import (
4 "context"
5 "errors"
6 "fmt"
7 "net/http"
8 "os"
9 "time"
10
iomodo3b0b9512021-03-15 00:13:06 +040011 "github.com/giolekva/pcloud/core/kg/common"
iomodob892d072021-02-22 00:23:16 +040012 "github.com/giolekva/pcloud/core/kg/log"
13 "github.com/giolekva/pcloud/core/kg/model"
14 "github.com/giolekva/pcloud/core/kg/store"
15 "github.com/gorilla/mux"
16)
17
18// HTTPServerImpl http server implementation
19type HTTPServerImpl struct {
iomodo3b0b9512021-03-15 00:13:06 +040020 Log common.LoggerIface
iomodob892d072021-02-22 00:23:16 +040021 srv *http.Server
22 root *mux.Router
23 config *model.Config
24 store store.Store
25}
26
27var _ Server = &HTTPServerImpl{}
28
29// NewHTTPServer creates new HTTP Server
iomodo3b0b9512021-03-15 00:13:06 +040030func NewHTTPServer(logger common.LoggerIface, config *model.Config, store store.Store) Server {
iomodob892d072021-02-22 00:23:16 +040031 a := &HTTPServerImpl{
32 Log: logger,
33 root: mux.NewRouter(),
34 config: config,
35 store: store,
36 }
37
38 pwd, _ := os.Getwd()
39 a.Log.Info("HTTP server current working", log.String("directory", pwd))
40 return a
41}
42
43// Start method starts a http server
44func (a *HTTPServerImpl) Start() error {
45 a.Log.Info("Starting HTTP Server...")
46
47 a.srv = &http.Server{
iomodoc0479a62021-02-22 20:08:36 +040048 Addr: fmt.Sprintf("%s:%d", a.config.HTTP.Host, a.config.HTTP.Port),
iomodob892d072021-02-22 00:23:16 +040049 Handler: a.root,
iomodoc0479a62021-02-22 20:08:36 +040050 ReadTimeout: time.Duration(a.config.HTTP.ReadTimeout) * time.Second,
51 WriteTimeout: time.Duration(a.config.HTTP.WriteTimeout) * time.Second,
52 IdleTimeout: time.Duration(a.config.HTTP.IdleTimeout) * time.Second,
iomodob892d072021-02-22 00:23:16 +040053 }
54
iomodoc0479a62021-02-22 20:08:36 +040055 a.Log.Info("HTTP Server is listening on", log.Int("port", a.config.HTTP.Port))
iomodob892d072021-02-22 00:23:16 +040056 if err := a.srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
iomodoc0479a62021-02-22 20:08:36 +040057 a.Log.Error("Failed to listen and serve: %v", log.Err(err))
iomodob892d072021-02-22 00:23:16 +040058 return err
59 }
60 return nil
61}
62
63// Shutdown method shuts http server down
64func (a *HTTPServerImpl) Shutdown() error {
65 a.Log.Info("Stopping HTTP Server...")
66 if a.srv == nil {
iomodoc0479a62021-02-22 20:08:36 +040067 return errors.New("No http server present")
iomodob892d072021-02-22 00:23:16 +040068 }
69
70 ctx, cancel := context.WithTimeout(context.Background(), time.Second)
71 defer cancel()
72 if err := a.srv.Shutdown(ctx); err != nil {
73 a.Log.Error("Unable to shutdown server", log.Err(err))
74 }
75
76 // a.srv.Close()
77 // a.srv = nil
78 a.Log.Info("HTTP Server stopped")
79 return nil
80}