forked from codeskyblue/gohttpserver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
201 lines (180 loc) · 5.7 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"runtime"
"strconv"
"strings"
"text/template"
"github.com/alecthomas/kingpin"
accesslog "github.com/codeskyblue/go-accesslog"
"github.com/go-yaml/yaml"
"github.com/goji/httpauth"
"github.com/gorilla/handlers"
)
type Configure struct {
Conf *os.File `yaml:"-"`
Addr string `yaml:"addr"`
Root string `yaml:"root"`
HTTPAuth string `yaml:"httpauth"`
Cert string `yaml:"cert"`
Key string `yaml:"key"`
Cors bool `yaml:"cors"`
Theme string `yaml:"theme"`
XHeaders bool `yaml:"xheaders"`
Upload bool `yaml:"upload"`
Delete bool `yaml:"delete"`
PlistProxy string `yaml:"plistproxy"`
Title string `yaml:"title"`
Debug bool `yaml:"debug"`
GoogleTrackerId string `yaml:"google-tracker-id"`
Auth struct {
Type string `yaml:"type"`
OpenID string `yaml:"openid"`
HTTP string `yaml:"http"`
} `yaml:"auth"`
}
type httpLogger struct{}
func (l httpLogger) Log(record accesslog.LogRecord) {
log.Printf("%s - %s %d %s", record.Ip, record.Method, record.Status, record.Uri)
}
var (
defaultPlistProxy = "https://plistproxy.herokuapp.com/plist"
defaultOpenID = "https://some-hostname.com/openid/"
gcfg = Configure{}
logger = httpLogger{}
VERSION = "unknown"
BUILDTIME = "unknown time"
GITCOMMIT = "unknown git commit"
SITE = "https://github.com/codeskyblue/gohttpserver"
)
func versionMessage() string {
t := template.Must(template.New("version").Parse(`GoHTTPServer
Version: {{.Version}}
Go version: {{.GoVersion}}
OS/Arch: {{.OSArch}}
Git commit: {{.GitCommit}}
Built: {{.Built}}
Site: {{.Site}}`))
buf := bytes.NewBuffer(nil)
t.Execute(buf, map[string]interface{}{
"Version": VERSION,
"GoVersion": runtime.Version(),
"OSArch": runtime.GOOS + "/" + runtime.GOARCH,
"GitCommit": GITCOMMIT,
"Built": BUILDTIME,
"Site": SITE,
})
return buf.String()
}
func parseFlags() error {
// initial default conf
gcfg.Root = "./"
gcfg.Addr = ":8000"
gcfg.Theme = "black"
gcfg.PlistProxy = defaultPlistProxy
gcfg.Auth.OpenID = defaultOpenID
gcfg.GoogleTrackerId = "UA-81205425-2"
gcfg.Title = "Go HTTP File Server"
kingpin.HelpFlag.Short('h')
kingpin.Version(versionMessage())
kingpin.Flag("conf", "config file path, yaml format").FileVar(&gcfg.Conf)
kingpin.Flag("root", "root directory, default ./").Short('r').StringVar(&gcfg.Root)
kingpin.Flag("addr", "listen address, default :8000").Short('a').StringVar(&gcfg.Addr)
kingpin.Flag("cert", "tls cert.pem path").StringVar(&gcfg.Cert)
kingpin.Flag("key", "tls key.pem path").StringVar(&gcfg.Key)
kingpin.Flag("auth-type", "Auth type <http|openid>").StringVar(&gcfg.Auth.Type)
kingpin.Flag("auth-http", "HTTP basic auth (ex: user:pass)").StringVar(&gcfg.Auth.HTTP)
kingpin.Flag("auth-openid", "OpenID auth identity url").StringVar(&gcfg.Auth.OpenID)
kingpin.Flag("theme", "web theme, one of <black|green>").StringVar(&gcfg.Theme)
kingpin.Flag("upload", "enable upload support").BoolVar(&gcfg.Upload)
kingpin.Flag("delete", "enable delete support").BoolVar(&gcfg.Delete)
kingpin.Flag("xheaders", "used when behide nginx").BoolVar(&gcfg.XHeaders)
kingpin.Flag("cors", "enable cross-site HTTP request").BoolVar(&gcfg.Cors)
kingpin.Flag("debug", "enable debug mode").BoolVar(&gcfg.Debug)
kingpin.Flag("plistproxy", "plist proxy when server is not https").Short('p').StringVar(&gcfg.PlistProxy)
kingpin.Flag("title", "server title").StringVar(&gcfg.Title)
kingpin.Flag("google-tracker-id", "set to empty to disable it").StringVar(&gcfg.GoogleTrackerId)
kingpin.Parse() // first parse conf
if gcfg.Conf != nil {
defer func() {
kingpin.Parse() // command line priority high than conf
}()
ymlData, err := ioutil.ReadAll(gcfg.Conf)
if err != nil {
return err
}
return yaml.Unmarshal(ymlData, &gcfg)
}
return nil
}
func main() {
if err := parseFlags(); err != nil {
log.Fatal(err)
}
if gcfg.Debug {
data, _ := yaml.Marshal(gcfg)
fmt.Printf("--- config ---\n%s\n", string(data))
}
log.SetFlags(log.Lshortfile | log.LstdFlags)
ss := NewHTTPStaticServer(gcfg.Root)
ss.Theme = gcfg.Theme
ss.Title = gcfg.Title
ss.GoogleTrackerId = gcfg.GoogleTrackerId
ss.Upload = gcfg.Upload
ss.Delete = gcfg.Delete
ss.AuthType = gcfg.Auth.Type
if gcfg.PlistProxy != "" {
u, err := url.Parse(gcfg.PlistProxy)
if err != nil {
log.Fatal(err)
}
u.Scheme = "https"
ss.PlistProxy = u.String()
}
var hdlr http.Handler = ss
hdlr = accesslog.NewLoggingHandler(hdlr, logger)
// HTTP Basic Authentication
userpass := strings.SplitN(gcfg.Auth.HTTP, ":", 2)
switch gcfg.Auth.Type {
case "http":
if len(userpass) == 2 {
user, pass := userpass[0], userpass[1]
hdlr = httpauth.SimpleBasicAuth(user, pass)(hdlr)
}
case "openid":
handleOpenID(false) // FIXME(ssx): set secure default to false
}
// CORS
if gcfg.Cors {
hdlr = handlers.CORS()(hdlr)
}
if gcfg.XHeaders {
hdlr = handlers.ProxyHeaders(hdlr)
}
http.Handle("/", hdlr)
http.HandleFunc("/-/sysinfo", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
data, _ := json.Marshal(map[string]interface{}{
"version": VERSION,
})
w.Write(data)
})
if !strings.Contains(gcfg.Addr, ":") {
gcfg.Addr = ":" + gcfg.Addr
}
log.Printf("listening on %s\n", strconv.Quote(gcfg.Addr))
var err error
if gcfg.Key != "" && gcfg.Cert != "" {
err = http.ListenAndServeTLS(gcfg.Addr, gcfg.Cert, gcfg.Key, nil)
} else {
err = http.ListenAndServe(gcfg.Addr, nil)
}
log.Fatal(err)
}