-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathstaticserver.go
101 lines (88 loc) · 2.22 KB
/
staticserver.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
package main
import (
"fmt"
"html/template"
"io"
"net/http"
"os"
"path/filepath"
"regexp"
"strconv"
"time"
)
var mux map[string]func(http.ResponseWriter, *http.Request)
type Myhandler struct{}
type home struct {
Title string
}
const (
Template_Dir = "./view/"
Upload_Dir = "./upload/"
)
func main() {
server := http.Server{
Addr: ":9090",
Handler: &Myhandler{},
ReadTimeout: 10 * time.Second,
}
mux = make(map[string]func(http.ResponseWriter, *http.Request))
mux["/"] = index
mux["/upload"] = upload
mux["/file"] = StaticServer
server.ListenAndServe()
}
func (*Myhandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if h, ok := mux[r.URL.String()]; ok {
h(w, r)
return
}
if ok, _ := regexp.MatchString("/css/", r.URL.String()); ok {
http.StripPrefix("/css/", http.FileServer(http.Dir("./css/"))).ServeHTTP(w, r)
} else {
http.StripPrefix("/", http.FileServer(http.Dir("./upload/"))).ServeHTTP(w, r)
}
}
func upload(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
t, _ := template.ParseFiles(Template_Dir + "file.html")
t.Execute(w, "上传文件")
} else {
r.ParseMultipartForm(32 << 20)
file, handler, err := r.FormFile("uploadfile")
if err != nil {
fmt.Fprintf(w, "%v", "上传错误")
return
}
fileext := filepath.Ext(handler.Filename)
if check(fileext) == false {
fmt.Fprintf(w, "%v", "不允许的上传类型")
return
}
filename := strconv.FormatInt(time.Now().Unix(), 10) + fileext
f, _ := os.OpenFile(Upload_Dir+filename, os.O_CREATE|os.O_WRONLY, 0660)
_, err = io.Copy(f, file)
if err != nil {
fmt.Fprintf(w, "%v", "上传失败")
return
}
filedir, _ := filepath.Abs(Upload_Dir + filename)
fmt.Fprintf(w, "%v", filename+"上传完成,服务器地址:"+filedir)
}
}
func index(w http.ResponseWriter, r *http.Request) {
title := home{Title: "首页"}
t, _ := template.ParseFiles(Template_Dir + "index.html")
t.Execute(w, title)
}
func StaticServer(w http.ResponseWriter, r *http.Request) {
http.StripPrefix("/file", http.FileServer(http.Dir("./upload/"))).ServeHTTP(w, r)
}
func check(name string) bool {
ext := []string{".exe", ".js", ".png"}
for _, v := range ext {
if v == name {
return false
}
}
return true
}