This repository has been archived by the owner on Jul 20, 2022. It is now read-only.
/
http.go
58 lines (51 loc) · 1.46 KB
/
http.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
package shared
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"github.com/go-kit/kit/endpoint"
http_transport "github.com/go-kit/kit/transport/http"
)
// MakeHandlerForEndpoint makes a HTTP handler for a given handler
func MakeHandlerForEndpoint(e endpoint.Endpoint) *http_transport.Server {
return http_transport.NewServer(e,
decodeHTTPRequest,
encodeHTTPReply,
http_transport.ServerErrorEncoder(httpErrorHandler),
)
}
// HasParameters returns if a query contains a list of parameters
func HasParameters(allParameters url.Values, parameters []string) bool {
for _, value := range parameters {
_, found := allParameters[value]
if !found {
return false
}
}
return true
}
// decodeHTTPRequest decodes the request
func decodeHTTPRequest(_ context.Context, req *http.Request) (interface{}, error) {
return req, nil
}
// encodeHTTPReply encodes the reply
func encodeHTTPReply(c context.Context, w http.ResponseWriter, rep interface{}) error {
var b bytes.Buffer
var enc = json.NewEncoder(&b)
enc.SetIndent("", " ")
if err := enc.Encode(rep); err != nil {
http.Error(w, err.Error(), 500)
return err
}
fmt.Fprintf(w, "%s", b.String())
return nil
}
// httpErrorHandler encodes the reply when there is an error.
func httpErrorHandler(ctx context.Context, err error, w http.ResponseWriter) {
w.Header().Set("Content-Type", "application/octet-stream")
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
}