/
main.go
83 lines (68 loc) · 1.35 KB
/
main.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
package main // import "ekyu.moe/h2s/cmd/h2s"
import (
"encoding/json"
"flag"
"log"
"net"
"os"
"ekyu.moe/h2s"
)
var (
stdout = log.New(os.Stdout, "", log.Ldate|log.Lmicroseconds)
stderr = log.New(os.Stderr, "", log.Ldate|log.Lmicroseconds)
)
type config struct {
*h2s.Config
Bind string `json:"bind"`
}
func main() {
n, conf := configure()
if n != 0 {
os.Exit(n)
}
s, err := h2s.NewServer(conf.Config)
if err != nil {
stderr.Println("h2s: create server:", err)
os.Exit(2)
}
defer s.Close()
l, err := net.Listen("tcp", conf.Bind)
if err != nil {
stderr.Println("h2s: bind:", err)
os.Exit(2)
}
stdout.Println("Listening on", l.Addr())
for {
conn, err := l.Accept()
if err != nil {
stderr.Println("h2s: accept:", err)
continue
}
go func() {
if err := s.Serve(conn); err != nil {
stderr.Println("h2s: serve:", err)
}
}()
}
}
func configure() (int, *config) {
configFilename := ""
flag.StringVar(&configFilename, "config", "h2s.json", "config file (json).")
flag.Parse()
f, err := os.Open(configFilename)
if err != nil {
stderr.Println("open config:", err)
return 1, nil
}
defer f.Close()
conf := &config{}
if err := json.NewDecoder(f).Decode(conf); err != nil {
stderr.Println("parse config:", err)
return 1, nil
}
f.Close()
if conf.Bind == "" {
conf.Bind = "127.0.0.1:0"
}
return 0, conf
}