-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
90 lines (84 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
package main
import (
"crypto/md5"
"fmt"
"html/template"
"io"
"log"
"net/http"
"os"
"strconv"
"strings"
"time"
)
func sayHelloName(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
fmt.Println(r.Form)
fmt.Println("path", r.URL.Path)
fmt.Println("scheme", r.URL.Scheme)
fmt.Println(r.Form["url_long"])
for k, v := range r.Form {
fmt.Println("key:", k)
fmt.Println("val:", strings.Join(v, ""))
}
fmt.Fprint(w, "Hello gopher!")
}
func login(w http.ResponseWriter, r *http.Request) {
fmt.Println("method: ", r.Method)
if r.Method == "GET" {
crutime := time.Now().Unix()
h := md5.New()
io.WriteString(h, strconv.FormatInt(crutime, 10))
token := fmt.Sprintf("%x", h.Sum(nil))
t, _ := template.ParseFiles("login.gtpl")
t.Execute(w, token)
} else {
r.ParseForm()
token := r.Form.Get("token")
if token != "" {
// validate token
} else {
// return error
}
fmt.Println("username: ", template.HTMLEscapeString(r.Form.Get("username")))
fmt.Println("password: ", template.HTMLEscapeString(r.Form.Get("password")))
}
}
func upload(w http.ResponseWriter, r *http.Request) {
fmt.Println("method: ", r.Method)
if r.Method == "GET" {
token := genToken()
t, _ := template.ParseFiles("upload.gtpl")
t.Execute(w, token)
} else {
r.ParseMultipartForm(32 << 20)
file, handler, err := r.FormFile("uploadfile")
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
fmt.Fprintf(w, "%v", handler.Header)
f, err := os.OpenFile("./test/"+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
io.Copy(f, file)
}
}
func serveSingle(pattern string, filename string) {
http.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, filename)
})
}
func main() {
serveSingle("/favicon.ico", "./favicon.ico")
http.HandleFunc("/", sayHelloName) // set router
http.HandleFunc("/login", login)
// set listen port
if err := http.ListenAndServe(":3001", nil); err != nil {
log.Fatal("ListenAndServer: ", err)
}
}