-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathfileserver.go
207 lines (176 loc) · 4.98 KB
/
fileserver.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
202
203
204
205
206
207
package gohttp
import (
"errors"
"fmt"
"html/template"
"io"
"log"
"mime"
"net"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"strings"
"time"
"github.com/itang/gotang"
)
const htmlTpl = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{{.CurrentPath}} - gohttp</title></head>
<link href="http://cdn.staticfile.org/twitter-bootstrap/2.3.2/css/bootstrap.min.css" rel="stylesheet">
<link href="http://cdn.staticfile.org/twitter-bootstrap/2.3.2/css/bootstrap-responsive.min.css" rel="stylesheet">
<body>
<div class="container-fluid">
<ul class="breadcrumb">
<li><a href="http://github.com/itang/gohttp">GOHTTP</a><span class="divider"> | </span></li>
<li><a href="#"><a href="/{{.ParentURI}}">{{.ParentPath}}</a><span class="divider"> | </span></li>
<li class="active"><a href="/{{.CurrentURI}}">{{.CurrentPath}}</a></li>
</ul>
<ul>
{{range .files}}
<li><a href="/{{.URI}}">{{.Name}}
{{if .Size }}
<small>({{.Size}})</small>
{{end}}
</a></li>
{{end}}</ul>
</div></body></html>`
var tmp = template.Must(template.New("index").Parse(htmlTpl))
type FileServer struct {
Port int
Webroot string
}
type Item struct {
Name string
Title string
URI string
Size int64
}
func lookupWlanIP4addr() (ip4 string, err error) {
addrs, err := net.InterfaceAddrs()
if err != nil {
return
}
for _, addr := range addrs {
if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
return ipnet.IP.String(), nil
}
}
}
return "", errors.New("No Found")
}
func tryGetLocalAddr() (ip string, err error) {
conn, err := net.DialTimeout("udp", "google.com:80", time.Millisecond*500)
if err != nil {
log.Println(err.Error())
return
}
defer conn.Close()
return strings.Split(conn.LocalAddr().String(), ":")[0], nil
}
func wlanIP4() string {
wip, err := tryGetLocalAddr()
if err != nil {
wip, err = lookupWlanIP4addr()
}
if err != nil {
wip = "Unknown"
}
return wip
}
func (fileServer *FileServer) Start() {
fileServer.router()
fmt.Printf("Serving HTTP on %s port %d from \"%s\" ... \n",
wlanIP4(), fileServer.Port, fileServer.Webroot,
)
addr := fmt.Sprintf(":%v", fileServer.Port)
log.Fatal(http.ListenAndServe(addr, nil))
}
func (fileServer *FileServer) ServeHTTP(w http.ResponseWriter, req *http.Request) {
defer func() {
if err := recover(); err != nil {
http.Error(w, fmt.Sprintf("%v", err), http.StatusInternalServerError)
}
}()
fileServer.handler(w, req)
}
func (fileServer *FileServer) router() {
http.Handle("/", fileServer)
}
var (
s1 = strings.Repeat(". ", (len("2013/11/19 21:16:13")+4)/2)
s2 = strings.Repeat("*", len("2013/11/19 21:16:13"))
)
func (fileServer *FileServer) handler(w http.ResponseWriter, req *http.Request) {
uri := req.RequestURI // 请求的URI, 如http://localhost:8080/hello -> /hello
if uri == "/favicon.ico" { // 不处理
return
}
traceInfo := fmt.Sprintf("%s \"%s\" from %v\n", req.Method, req.RequestURI, req.RemoteAddr)
fullpath, relpath := fileServer.requestURIToFilepath(uri)
traceInfo += fmt.Sprintf("%sTo Filepath: %v\n", s1, fullpath)
file, err := os.Open(fullpath)
if err != nil || os.IsNotExist(err) { // 文件不存在
traceInfo += s1 + "NotFound!\n"
http.NotFound(w, req)
} else {
stat, _ := file.Stat()
if stat.IsDir() {
traceInfo += s1 + "Process Dir...\n"
fileServer.processDir(w, file, fullpath, relpath)
} else {
traceInfo += s1 + "Send File...\n"
fileServer.sendFile(w, file, fullpath, relpath)
}
}
log.Println(traceInfo + s2 + " END")
}
func (fileServer *FileServer) requestURIToFilepath(uri string) (fullpath string, relpath string) {
unescapeIt, _ := url.QueryUnescape(uri)
relpath = unescapeIt
fullpath = filepath.Join(fileServer.Webroot, relpath[1:])
return
}
func (_ *FileServer) processDir(w http.ResponseWriter, dir *os.File, fullpath string, relpath string) {
w.Header().Set("Content-type", "text/html; charset=UTF-8")
fis, err := dir.Readdir(-1)
gotang.AssertNoError(err, "读取文件夹信息出错!")
items := make([]Item, 0, len(fis))
for _, fi := range fis {
var size int64
if !fi.IsDir() {
size = fi.Size()
}
item := Item{
Name: fi.Name(),
Title: fi.Name(),
URI: url.PathEscape(path.Join(relpath, fi.Name())),
Size: size,
}
items = append(items, item)
}
parentPath, currentPath := path.Dir(relpath), relpath
tmp.Execute(w, map[string]interface{}{
"ParentPath": parentPath,
"CurrentPath": currentPath,
"ParentURI": url.PathEscape(parentPath),
"CurrentURI": url.PathEscape(currentPath),
"files": items,
})
}
func (_ *FileServer) sendFile(w http.ResponseWriter, file *os.File, fullpath string, relpath string) {
if mimetype := mime.TypeByExtension(path.Ext(file.Name())); mimetype != "" {
w.Header().Set("Content-Type", mimetype)
} else {
w.Header().Set("Content-Type", "application/octet-stream")
}
statinfo, _ := file.Stat()
w.Header().Set("Content-Length", fmt.Sprintf("%v", statinfo.Size()))
io.Copy(w, file)
}