forked from asbubam/examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.go
63 lines (49 loc) · 1.27 KB
/
api.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
package main
import (
"encoding/json"
"log"
"strings"
hello "github.com/micro/examples/greeter/srv/proto/hello"
"github.com/micro/go-micro/v2"
"github.com/micro/go-micro/v2/errors"
shard "github.com/micro/go-plugins/wrapper/select/shard/v2"
api "github.com/micro/micro/v2/api/proto"
"context"
)
type Say struct {
Client hello.SayService
}
func (s *Say) Hello(ctx context.Context, req *api.Request, rsp *api.Response) error {
log.Print("Received Say.Hello API request")
name, ok := req.Get["name"]
if !ok || len(name.Values) == 0 {
return errors.BadRequest("go.micro.api.greeter", "Name cannot be blank")
}
response, err := s.Client.Hello(ctx, &hello.Request{
Name: strings.Join(name.Values, " "),
})
if err != nil {
return err
}
rsp.StatusCode = 200
b, _ := json.Marshal(map[string]string{
"message": response.Msg,
})
rsp.Body = string(b)
return nil
}
func main() {
wrapper := shard.NewClientWrapper("X-From-User")
service := micro.NewService(
micro.Name("go.micro.api.greeter"),
micro.WrapClient(wrapper),
)
// parse command line flags
service.Init()
service.Server().Handle(service.Server().NewHandler(&Say{
Client: hello.NewSayService("go.micro.srv.greeter", service.Client()),
}))
if err := service.Run(); err != nil {
log.Fatal(err)
}
}