-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.go
66 lines (53 loc) · 1.33 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
64
65
66
package main
import (
"encoding/json"
"log"
"strings"
// 引用上面生成的proto文件
api "github.com/micro/go-api/proto"
"github.com/micro/go-micro/errors"
"github.com/micro/go-micro/v2"
proto "helloworld/proto"
"context"
)
type Say struct {
Client proto.GreeterService
}
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")
}
log.Println("name: %s", name.Values)
response, err := s.Client.Hello(ctx, &proto.HelloRequest{
Name: strings.Join(name.Values, " "),
})
if err != nil {
return err
}
rsp.StatusCode = 200
b, _ := json.Marshal(map[string]string{
"message": response.Greeting,
})
rsp.Body = string(b)
return nil
}
func main() {
// new一个微服务出来 资源类型设置为api
service := micro.NewService(
micro.Name("go.micro.api.greeter"),
)
// 可选 解析命令行
service.Init()
// 注册handler
service.Server().Handle(
service.Server().NewHandler(
//&Say{Client: proto.NewGreeterService("go.micro.srv.greeter", service.Client())},
&Say{Client: proto.NewGreeterService("greeter", service.Client())},
),
)
if err := service.Run(); err != nil {
log.Fatal(err)
}
}