Core

/app/cmd/util.go (2.4 KB)

  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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package cmd

import (
"fmt"
"net"
"strconv"
"sync"

"github.com/kirsle/configdir"
"github.com/pkg/errors"
"github.com/valyala/fasthttp"

"{{{ .Package }}}/app"
"{{{ .Package }}}/app/lib/log"
"{{{ .Package }}}/app/util"
)

var (
_initialized = false
_buildInfo *app.BuildInfo
_flags = &Flags{}
_logger util.Logger
)

type Flags struct {
Address string
Port uint16
ConfigDir string
Debug bool
}

func (f *Flags) Addr() string {
if f.Port == 0 {
return f.Address
}
return fmt.Sprintf("%s:%d", f.Address, f.Port)
}

func (f *Flags) Clone(port uint16) *Flags {
return &Flags{
Address: f.Address,
Port: port,
ConfigDir: f.ConfigDir,
Debug: f.Debug,
}
}

var initMu sync.Mutex

func initIfNeeded() error {
initMu.Lock()
defer initMu.Unlock()

if _initialized {
return nil
}
if _buildInfo == nil {
return errors.New("no build info")
}
if _flags.ConfigDir == "" {
_flags.ConfigDir = configdir.LocalConfig(util.AppName)
_ = configdir.MakePath(_flags.ConfigDir)
}
l, err := log.InitLogging(_flags.Debug)
if err != nil {
return err
}
_logger = l
_initialized = true
return nil
}

func listen(address string, port uint16) (uint16, net.Listener, error) {
l, err := net.Listen("tcp", fmt.Sprintf("%s:%d", address, port))
if err != nil {
return port, nil, errors.Wrapf(err, "unable to listen on port [%d]", port)
}
if port == 0 {
addr := l.Addr().String()
_, portStr := util.StringSplitLast(addr, ':', true)
actualPort, err := strconv.ParseUint(portStr, 10, 16)
if err != nil {
return 0, nil, errors.Wrapf(err, "invalid port [%s]", portStr)
}
port = uint16(actualPort)
}
return port, l, nil
}

var (
maxHeaderSize = 1024 * 256
maxBodySize = 1024 * 1024 * 128
)

func serve(name string, listener net.Listener, h fasthttp.RequestHandler) error {
x := &fasthttp.Server{Handler: h, Name: name, ReadBufferSize: maxHeaderSize, NoDefaultServerHeader: true, MaxRequestBodySize: maxBodySize}
if err := x.Serve(listener); err != nil {
return errors.Wrap(err, "unable to run http server")
}
return nil
}

func listenandserve(name string, addr string, port uint16, h fasthttp.RequestHandler) (uint16, error) {
p, l, err := listen(addr, port)
if err != nil {
return p, err
}
err = serve(name, l, h)
if err != nil {
return p, err
}
return 0, nil
}