forked from go-kit/kit
/
full.go
60 lines (49 loc) · 1.44 KB
/
full.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
package foo
import (
"context"
"encoding/json"
"errors"
"net/http"
"github.com/go-kit/kit/endpoint"
httptransport "github.com/go-kit/kit/transport/http"
)
type ExampleService struct {
}
type ExampleRequest struct {
I int
S string
}
type ExampleResponse struct {
S string
Err error
}
type Endpoints struct {
ExampleEndpoint endpoint.Endpoint
}
func (f ExampleService) ExampleEndpoint(ctx context.Context, i int, s string) (string, error) {
panic(errors.New("not implemented"))
}
func makeExampleEndpoint(f ExampleService) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
req := request.(ExampleRequest)
s, err := f.ExampleEndpoint(ctx, req.I, req.S)
return ExampleResponse{S: s, Err: err}, nil
}
}
func inlineHandlerBuilder(m *http.ServeMux, endpoints Endpoints) {
m.Handle("/bar", httptransport.NewServer(endpoints.ExampleEndpoint, DecodeExampleRequest, EncodeExampleResponse))
}
func NewHTTPHandler(endpoints Endpoints) http.Handler {
m := http.NewServeMux()
inlineHandlerBuilder(m, endpoints)
return m
}
func DecodeExampleRequest(_ context.Context, r *http.Request) (interface{}, error) {
var req ExampleRequest
err := json.NewDecoder(r.Body).Decode(&req)
return req, err
}
func EncodeExampleResponse(_ context.Context, w http.ResponseWriter, response interface{}) error {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
return json.NewEncoder(w).Encode(response)
}