-
Notifications
You must be signed in to change notification settings - Fork 0
/
responder.go
53 lines (45 loc) · 1.01 KB
/
responder.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
package responder
import (
"net/http"
"path/filepath"
"strings"
)
type Responder struct {
responds map[string]func()
}
func With(format string, fc func()) *Responder {
rep := &Responder{responds: map[string]func(){}}
return rep.With(format, fc)
}
func (rep *Responder) With(format string, fc func()) *Responder {
rep.responds[format] = fc
return rep
}
func (rep *Responder) Respond(writer http.ResponseWriter, request *http.Request) {
format := "html"
if ext := filepath.Ext(request.URL.Path); ext != "" {
format = strings.TrimPrefix(ext, ".")
}
if request.Header.Get("Content-Type") == "application/json" {
format = "json"
} else {
for _, str := range strings.Split(request.Header.Get("Accept"), ",") {
if str == "application/json" {
format = "json"
if writer != nil {
writer.Header().Set("Content-Type", "application/json")
}
break
}
}
}
if fc, ok := rep.responds[format]; ok {
fc()
return
}
for _, respond := range rep.responds {
respond()
break
}
return
}