Passed
Push — master ( f80f95...7fc31c )
by Igor
06:13 queued 02:21
created

server.New   A

Complexity

Conditions 1

Size

Total Lines 10
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 10
nop 3
dl 0
loc 10
rs 9.9
c 0
b 0
f 0
1
package server
2
3
import (
4
	"context"
5
	"errors"
6
	"fmt"
7
	"log"
8
	"net/http"
9
	"os"
10
	"os/signal"
11
	"syscall"
12
	"time"
13
)
14
15
type httpServer struct {
16
	server *http.Server
17
}
18
19
func New(port uint16, handler http.Handler, logger *log.Logger) Server {
20
	return &httpServer{
21
		server: &http.Server{
22
			Addr:           fmt.Sprintf(":%d", port),
23
			Handler:        handler,
24
			ErrorLog:       logger,
25
			ReadTimeout:    5 * time.Second,
26
			WriteTimeout:   10 * time.Second,
27
			IdleTimeout:    30 * time.Second,
28
			MaxHeaderBytes: 1 << 20,
29
		},
30
	}
31
}
32
33
func (httpServer *httpServer) Run() error {
34
	hostname, err := os.Hostname()
35
	if err != nil {
36
		return err
37
	}
38
39
	done := make(chan bool)
40
	quit := make(chan os.Signal, 1)
41
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
42
43
	go func() {
44
		<-quit
45
		httpServer.server.ErrorLog.Printf("%s - Shutdown signal received...\n", hostname)
46
47
		ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
48
		defer cancel()
49
50
		httpServer.server.SetKeepAlivesEnabled(false)
51
52
		if err := httpServer.server.Shutdown(ctx); err != nil {
53
			httpServer.server.ErrorLog.Fatalf("Could not gracefully shutdown the server: %v\n", err)
54
		}
55
56
		close(done)
57
	}()
58
59
	httpServer.server.ErrorLog.Printf("%s - Starting server on port %v", hostname, httpServer.server.Addr)
60
61
	if err := httpServer.server.ListenAndServe(); errors.Is(err, http.ErrServerClosed) {
62
		httpServer.server.ErrorLog.Fatalf("Could not listen on %s: %v\n", httpServer.server.Addr, err)
63
	}
64
65
	<-done
66
	httpServer.server.ErrorLog.Printf("%s - Server has been gracefully stopped.\n", hostname)
67
68
	return nil
69
}
70