-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
61 lines (51 loc) · 1.49 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
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"path/filepath"
"strings"
"github.com/tonny-zhang/cotton"
)
func main() {
r := cotton.Default()
// Content-Type is "application/x-www-form-urlencoded" or "multipart/form-data"
r.Post("/post", func(ctx *cotton.Context) {
q := ctx.GetQuery("q")
str := ctx.GetPostForm("str")
ids := ctx.GetPostFormArray("ids")
m, _ := ctx.GetPostFormMap("info")
ctx.String(http.StatusOK, fmt.Sprintf("q = %s, str = %s, ids = %v, info = %v", q, str, ids, m))
})
dirSave := filepath.Dir(os.Args[0])
r.Post("/upload", func(ctx *cotton.Context) {
name := ctx.GetPostForm("name")
fileheader := ctx.GetPostFormFile("file")
files := ctx.GetPostFormFileArray("filelist")
infos := make([]string, len(files))
for i, file := range files {
saveto := filepath.Join(dirSave, "upload", file.Filename)
e := ctx.SavePostFormFile(file, saveto)
if e == nil {
infos[i] = file.Filename + " save to " + saveto
} else {
infos[i] = file.Filename + " has err: " + e.Error()
}
}
ctx.String(http.StatusOK, "name = "+name+", file.Name = "+fileheader.Filename+"\n"+strings.Join(infos, "\n"))
})
// Content-Type is "application/json"
r.Post("/json", func(ctx *cotton.Context) {
ct := ctx.GetRequestHeader("Content-Type")
if ct == "application/json" {
body := ctx.Request.Body
if body != nil {
obj := make(map[string]interface{})
json.NewDecoder(body).Decode(&obj)
ctx.JSON(http.StatusOK, obj)
}
}
})
r.Run("")
}