-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler.go
45 lines (41 loc) · 1.01 KB
/
handler.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
package coco
import (
"encoding/json"
"fmt"
"github.com/julienschmidt/httprouter"
"mime"
"net/http"
"strconv"
"strings"
)
//Handler 所有 handler 都会被转换成该类型
type Handler func(coco *Coco) Result
func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
panic(err)
}
coco := NewCoco()
coco.Request = r
coco.ResponseWriter = w
coco.Params = httprouter.ParamsFromContext(r.Context())
resp := h(coco)
var response []byte
if resp.Type == "binary" {
response = resp.BinaryData
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", resp.FileName))
w.Header().Set("Content-Type", MimeTypeByName(resp.FileName))
w.Header().Set("Content-Length", strconv.Itoa(len(response)))
} else {
response, err = json.Marshal(resp)
if err != nil {
panic(err)
}
}
w.Write(response)
}
func MimeTypeByName(name string) string {
names := strings.Split(name, ".")
ext := "." + names[len(names)-1]
return mime.TypeByExtension(ext)
}