-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhelpers.go
39 lines (33 loc) · 1.17 KB
/
helpers.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
package middleware
import (
"encoding/json"
"net/http"
)
// Param returns the value for a parameter in the URL.
func Param(r *http.Request, key string) string {
params, ok := r.Context().Value(paramsKey).(map[string]string)
if !ok {
return ""
}
return params[key]
}
// Text responds to a request with a string in plain text.
func Text(w http.ResponseWriter, r *http.Request, v string) (int, error) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
return w.Write([]byte(v))
}
// JSON responds to a request with arbitrary data in JSON format.
func JSON(w http.ResponseWriter, r *http.Request, v interface{}) error {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
return json.NewEncoder(w).Encode(v)
}
// HTML responds to a request with an arbitrary string as HTML.
func HTML(w http.ResponseWriter, r *http.Request, v string) (int, error) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
return w.Write([]byte(v))
}
// Data responds to a request with an arbitrary slice of bytes.
func Data(w http.ResponseWriter, r *http.Request, v []byte) (int, error) {
w.Header().Set("Content-Type", "application/octet-stream")
return w.Write(v)
}