-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathutils.go
75 lines (66 loc) · 2 KB
/
utils.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package main
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os/exec"
"time"
"github.com/julienschmidt/httprouter"
"github.com/pkg/errors"
)
type requestHandlerWithContext func(context.Context, http.ResponseWriter, httprouter.Params) error
type requestHandler func(http.ResponseWriter, httprouter.Params) error
func makeRequestHandlerWithContext(h requestHandlerWithContext) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
defer cancel()
err := h(ctx, w, ps)
if err != nil {
errMsg := fmt.Sprintf("An error occured: %s", err)
http.Error(w, errMsg, http.StatusInternalServerError)
return
}
}
}
func makeRequestHandler(h requestHandler) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
err := h(w, ps)
if err != nil {
errMsg := fmt.Sprintf("An error occured: %s", err)
http.Error(w, errMsg, http.StatusInternalServerError)
return
}
}
}
func makeRequestHandlerCommand(desc string, cmdName string, cmdArg ...string) httprouter.Handle {
return makeRequestHandlerWithContext(func(ctx context.Context, w http.ResponseWriter, ps httprouter.Params) error {
cmd := exec.CommandContext(ctx, cmdName, cmdArg...)
output, err := cmd.Output()
if err != nil {
return errors.Wrapf(err, "Error fetching %s", desc)
}
w.Write(output)
return nil
})
}
func makeRequestHandlerFile(desc string, path string) httprouter.Handle {
return makeRequestHandler(func(w http.ResponseWriter, ps httprouter.Params) error {
output, err := ioutil.ReadFile(path)
if err != nil {
return errors.Wrapf(err, "Error fetching %s", desc)
}
w.Write(output)
return nil
})
}
func returnJSON(w http.ResponseWriter, item interface{}) error {
resp, err := json.Marshal(item)
if err != nil {
return errors.Wrap(err, "Error converting response to JSON")
}
w.Header().Set("Content-Type", "application/json")
w.Write(resp)
return nil
}