-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.go
61 lines (53 loc) · 1.25 KB
/
server.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 knockttp
import (
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"text/template"
)
type TestServer struct {
*httptest.Server
Data map[string]interface{}
Routes Routes
}
func NewTestServer(routes Routes) (*TestServer, error) {
mux := http.NewServeMux()
server := httptest.NewServer(mux)
ts := TestServer{
Server: server,
Data: map[string]interface{}{
"BaseURL": server.URL,
},
Routes: routes,
}
for _, route := range ts.Routes {
for method, handler := range route.Methods {
if handler.Filename != "" {
buff, err := ioutil.ReadFile(handler.Filename)
if err != nil {
panic(err)
}
t := template.New(method + " " + route.Path)
handler.template, err = t.Parse(string(buff))
if err != nil {
return nil, err
}
}
}
mux.HandleFunc(route.Path, ts.ServeFunc(route))
}
return &ts, nil
}
func (ts *TestServer) ServeFunc(route *Route) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
m, ok := route.GetHandler(r.Method)
if !ok {
w.WriteHeader(http.StatusInternalServerError)
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte(fmt.Sprintf("unsupported method: '%s'", r.Method)))
return
}
m.Handle(w, r, ts.Data)
}
}