/
echo.go
86 lines (66 loc) · 1.62 KB
/
echo.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
76
77
78
79
80
81
82
83
84
85
package echo
import (
"encoding/json"
"errors"
// "log"
"net/http"
"fmt"
// "strings"
"golang.org/x/net/context"
"github.com/go-kit/kit/endpoint"
httptransport "github.com/go-kit/kit/transport/http"
)
type EchoService interface {
Echo(string) (string, error)
}
type echoService struct {}
var ErrEmpty = errors.New("empty string")
func (echoService) Echo(s string) (string, error) {
if s == "" {
return "", ErrEmpty
}
return s, nil
}
func decodeEchoRequest(r *http.Request) (interface{}, error) {
var request echoRequest
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
return nil, err
}
return request, nil
}
func encodeResponse(w http.ResponseWriter, response interface{}) error {
return json.NewEncoder(w).Encode(response)
}
func makeEchoEndpoint(svc EchoService) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
req := request.(echoRequest)
v, err := svc.Echo(req.S)
if err != nil {
return echoResponse{v, err.Error()}, nil
}
return echoResponse{v, ""}, nil
}
}
type echoRequest struct {
S string `json:"s"`
}
type echoResponse struct {
V string `json:"v"`
Err string `json:"err,omitempty"`
}
func hello(w http.ResponseWriter, r *http.Request){
fmt.Fprint(w, "Hello 123")
}
func init() {
ctx := context.Background()
svc := echoService{}
echoHandler := httptransport.NewServer(
ctx,
makeEchoEndpoint(svc),
decodeEchoRequest,
encodeResponse,
)
http.HandleFunc("/", hello)
http.Handle("/echo", echoHandler)
// log.Fatal(http.ListenAndServe(":8080", nil))
}