-
Notifications
You must be signed in to change notification settings - Fork 49
/
client.go
82 lines (73 loc) · 2.15 KB
/
client.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
// Copyright 2022 Lingfei Kong <colin404@foxmail.com>. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file. The original repo for
// this file is https://github.com/superproj/onex.
//
package main
import (
"context"
"log"
"github.com/go-kratos/kratos/v2/errors"
"github.com/go-kratos/kratos/v2/middleware/recovery"
transgrpc "github.com/go-kratos/kratos/v2/transport/grpc"
transhttp "github.com/go-kratos/kratos/v2/transport/http"
v1 "github.com/superproj/onex/pkg/api/usercenter/v1"
)
func main() {
callHTTP()
callGRPC()
}
func callHTTP() {
conn, err := transhttp.NewClient(
context.Background(),
transhttp.WithMiddleware(
recovery.Recovery(),
),
transhttp.WithEndpoint("onex.usercenter.superproj.com:18080"),
)
if err != nil {
panic(err)
}
defer conn.Close()
client := v1.NewUserCenterHTTPClient(conn)
reply, err := client.Login(context.Background(), &v1.LoginRequest{Username: "colin", Password: "onex(#)666"})
if err != nil {
log.Fatal(err)
}
log.Printf("[http] Login %s\n", reply.RefreshToken)
// returns error
_, err = client.Login(context.Background(), &v1.LoginRequest{Username: "colin", Password: "badpassword"})
if err != nil {
log.Printf("[http] Login error: %v\n", err)
}
if errors.IsBadRequest(err) {
log.Printf("[http] Login error is invalid argument: %v\n", err)
}
}
func callGRPC() {
conn, err := transgrpc.DialInsecure(
context.Background(),
transgrpc.WithEndpoint("onex.usercenter.superproj.com:18080"),
transgrpc.WithMiddleware(
recovery.Recovery(),
),
)
if err != nil {
panic(err)
}
defer conn.Close()
client := v1.NewUserCenterClient(conn)
reply, err := client.Login(context.Background(), &v1.LoginRequest{Username: "colin", Password: "onex(#)666"})
if err != nil {
log.Fatal(err)
}
log.Printf("[grpc] Login %+v\n", reply.RefreshToken)
// returns error
_, err = client.Login(context.Background(), &v1.LoginRequest{Username: "colin", Password: "badpassword"})
if err != nil {
log.Printf("[grpc] Login error: %v\n", err)
}
if errors.IsBadRequest(err) {
log.Printf("[grpc] Login error is invalid argument: %v\n", err)
}
}