-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathutil.go
117 lines (103 loc) · 2.36 KB
/
util.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
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
114
115
116
117
// Package cmd - Content managed by Project Forge, see [projectforge.md] for details.
package cmd
import (
"fmt"
"net"
"net/http"
"strconv"
"sync"
"time"
"github.com/kirsle/configdir"
"github.com/pkg/errors"
"projectforge.dev/projectforge/app"
"projectforge.dev/projectforge/app/lib/log"
"projectforge.dev/projectforge/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)
}
err := util.InitAcronyms()
if err != nil {
return err
}
l, err := log.InitLogging(_flags.Debug)
if err != nil {
return err
}
util.DEBUG = _flags.Debug
_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
func serve(listener net.Listener, h http.Handler) error {
x := &http.Server{Handler: h, MaxHeaderBytes: maxHeaderSize, ReadHeaderTimeout: time.Minute}
if err := x.Serve(listener); err != nil {
return errors.Wrap(err, "unable to run http server")
}
return nil
}
func listenandserve(addr string, port uint16, h http.Handler) (uint16, error) {
p, l, err := listen(addr, port)
if err != nil {
return p, err
}
err = serve(l, h)
if err != nil {
return p, err
}
return 0, nil
}