forked from golang101/golang101
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
102 lines (86 loc) · 2.04 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package main
import (
"context"
"flag"
"fmt"
"log"
"net"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"
)
var portFlag = flag.String("port", "12345", "server port")
var genFlag = flag.Bool("gen", false, "HTML generation mode?")
var themeFlag = flag.String("theme", "", "theme (dark | light)")
var nobFlag = flag.Bool("nob", false, "not open browswer?")
var listenConfig net.ListenConfig
func main() {
log.SetFlags(0)
flag.Parse()
port, isAppEngine := *portFlag, false
if prt := os.Getenv("PORT"); prt != "" { // appengine std
port = prt
isAppEngine = true
}
addr, err := net.ResolveTCPAddr("tcp", fmt.Sprintf(":%v", port))
if err != nil {
log.Fatal(err)
}
Retry:
//l, err := net.ListenTCP("tcp", addr)
l, err := listenConfig.Listen(context.Background(), "tcp", addr.String())
if err != nil {
if strings.Index(err.Error(), "bind: address already in use") >= 0 {
addr.Port++
if addr.Port < 65535 {
goto Retry
}
}
log.Fatal(err)
}
defer l.Close()
go101.theme = *themeFlag
genMode, rootURL := *genFlag, fmt.Sprintf("http://localhost:%v/", addr.Port)
if !genMode && !isAppEngine {
if !*nobFlag {
err = openBrowser(rootURL)
if err != nil {
log.Println(err)
}
}
go updateGolang101()
}
httpServer := &http.Server{
Handler: go101,
WriteTimeout: 10 * time.Second,
ReadTimeout: 5 * time.Second,
}
runServer := func() {
log.Println("Server started:")
log.Printf(" http://localhost:%v (non-cached version)\n", addr.Port)
log.Printf(" http://127.0.0.1:%v (cached version)\n", addr.Port)
httpServer.Serve(l)
}
shutdownServer := func() {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := httpServer.Shutdown(ctx); err != nil {
log.Fatalf("Server shutdown error: %s", err)
}
log.Println("Server shutdown.")
}
if genMode {
go runServer()
genStaticFiles(rootURL)
shutdownServer()
return
}
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
go runServer()
<-c
shutdownServer()
}