-
Notifications
You must be signed in to change notification settings - Fork 21
/
server.go
64 lines (54 loc) · 1.64 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
// Copyright © 2018 by PACE Telematics GmbH. All rights reserved.
// Created at 2018/09/06 by Vincent Landgraf
package http
import (
golog "log"
"net/http"
"strconv"
"time"
"github.com/caarlos0/env"
"github.com/pace/bricks/maintenance/log"
)
func init() {
parseConfig()
}
type config struct {
Addr string `env:"ADDR"`
Port int `env:"PORT" envDefault:"3000"`
Environment string `env:"ENVIRONMENT" envDefault:"edge"`
MaxHeaderBytes int `env:"MAX_HEADER_BYTES" envDefault:"1048576"` // 1MB
IdleTimeout time.Duration `env:"IDLE_TIMEOUT" envDefault:"1h"`
ReadTimeout time.Duration `env:"READ_TIMEOUT" envDefault:"60s"`
WriteTimeout time.Duration `env:"WRITE_TIMEOUT" envDefault:"60s"`
}
// addrOrPort returns ADDR if it is defined, otherwise PORT is used
func (cfg config) addrOrPort() string {
if cfg.Addr != "" {
return cfg.Addr
}
return ":" + strconv.Itoa(cfg.Port)
}
var cfg config
func parseConfig() {
err := env.Parse(&cfg)
if err != nil {
log.Fatalf("Failed to parse server environment: %v", err)
}
}
// Server returns a http.Server configured using environment variables,
// following https://12factor.net/.
func Server(handler http.Handler) *http.Server {
return &http.Server{
Addr: cfg.addrOrPort(),
Handler: handler,
ReadTimeout: cfg.ReadTimeout,
WriteTimeout: cfg.WriteTimeout,
MaxHeaderBytes: cfg.MaxHeaderBytes,
IdleTimeout: cfg.IdleTimeout,
ErrorLog: golog.New(log.Logger(), "[http.Server] ", 0),
}
}
// Environment returns the name of the current server environment
func Environment() string {
return cfg.Environment
}