-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.go
37 lines (31 loc) · 814 Bytes
/
router.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
package http_server_mock
import (
"fmt"
"github.com/anthonysyk/http-server-mock/pkg/routehelper"
"github.com/gorilla/mux"
"net/http"
)
func GenerateRouter(config string) (*mux.Router, error) {
router := mux.NewRouter()
routes, err := GetRoutes(config)
if err != nil {
return nil, err
}
for _, r := range routes {
router.HandleFunc(r.URL, handler(r)).Methods(r.Method)
}
routehelper.PrintRoutes(router)
return router, nil
}
func handler(route Route) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
content, err := route.GetBody(mux.Vars(r))
if err != nil {
w.WriteHeader(http.StatusNotFound)
return
}
w.WriteHeader(route.StatusCode)
fmt.Fprintf(w, string(content))
}
}