Skip to content

Commit eda7e25

Browse files
committed
feat(grpc): grpc call
1 parent 80f0c3e commit eda7e25

File tree

7 files changed

+352
-370
lines changed

7 files changed

+352
-370
lines changed

.github/workflows/go.yml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,10 @@ jobs:
1212
runs-on: ubuntu-latest
1313
steps:
1414

15-
- name: load Go 1.17 env
15+
- name: load Go 1.18 env
1616
uses: actions/setup-go@v3
1717
with:
18-
go-version: 1.17
18+
go-version: 1.18
1919
id: go
2020

2121
- name: checkout

cmd/auth/auth.go

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
package auth
2+
3+
import (
4+
"context"
5+
"fmt"
6+
"log"
7+
"net"
8+
"net/http"
9+
"net/url"
10+
"time"
11+
12+
authv1 "github.com/hduhelp/api_open_sdk/gatewayapis/auth/v1"
13+
grpcclient "github.com/hduhelp/api_open_sdk/grpcClient"
14+
"github.com/hduhelp/hdu-cli/pkg/table"
15+
"github.com/spf13/cobra"
16+
"github.com/spf13/viper"
17+
"google.golang.org/protobuf/types/known/emptypb"
18+
)
19+
20+
var Cmd = &cobra.Command{
21+
Use: "auth",
22+
}
23+
24+
func init() {
25+
Cmd.AddCommand(loginCmd, logoutCmd, infoCmd)
26+
27+
loginCmd.Flags().StringP("token", "t", "", "hduhelp token")
28+
}
29+
30+
var loginCmd = &cobra.Command{
31+
Use: "login",
32+
Run: func(cmd *cobra.Command, args []string) {
33+
ctx := context.Background()
34+
argToken := cmd.Flags().Lookup("token").Value.String()
35+
if argToken != "" {
36+
tokenVerify(ctx, argToken)
37+
return
38+
}
39+
ln, err := net.Listen("tcp", ":11328")
40+
if err != nil {
41+
log.Fatalln(err)
42+
}
43+
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
44+
token := r.URL.Query().Get("auth")
45+
w.Write([]byte("login success, now return to cli"))
46+
tokenVerify(ctx, token)
47+
go func() {
48+
time.Sleep(time.Second)
49+
ln.Close()
50+
}()
51+
})
52+
loginUrl, _ := url.Parse("https://api.hduhelp.com/login/auto")
53+
loginUrl.RawQuery = url.Values{
54+
"clientID": {"dashboard"},
55+
"redirect": {"http://localhost:11328"},
56+
}.Encode()
57+
fmt.Println(loginUrl)
58+
http.Serve(ln, http.DefaultServeMux)
59+
},
60+
}
61+
62+
func tokenVerify(ctx context.Context, token string) {
63+
client := authv1.NewAuthServiceClient(grpcclient.Conn(ctx))
64+
info, err := client.GetTokenInfo(grpcclient.WithToken(ctx, token), &emptypb.Empty{})
65+
if err != nil {
66+
log.Fatalln(err)
67+
}
68+
table.PrintStruct(info)
69+
viper.Set("auth.token", token)
70+
err = viper.WriteConfig()
71+
cobra.CheckErr(err)
72+
}
73+
74+
var logoutCmd = &cobra.Command{
75+
Use: "logout",
76+
Run: func(cmd *cobra.Command, args []string) {
77+
viper.Set("auth.token", "")
78+
err := viper.WriteConfig()
79+
cobra.CheckErr(err)
80+
fmt.Println("logout success")
81+
},
82+
}
83+
84+
var infoCmd = &cobra.Command{
85+
Use: "info",
86+
Run: func(cmd *cobra.Command, args []string) {
87+
ctx := context.Background()
88+
token := viper.GetString("auth.token")
89+
if token == "" {
90+
log.Fatalf("auth token not found")
91+
}
92+
client := authv1.NewAuthServiceClient(grpcclient.Conn(ctx))
93+
info, err := client.GetTokenInfo(grpcclient.WithToken(ctx, token), &emptypb.Empty{})
94+
if err != nil {
95+
fmt.Println(err)
96+
} else {
97+
table.PrintStruct(info)
98+
}
99+
},
100+
}

cmd/cmd.go

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,13 @@ package cmd
22

33
import (
44
"fmt"
5+
"os"
6+
7+
"github.com/hduhelp/hdu-cli/cmd/auth"
58
"github.com/hduhelp/hdu-cli/cmd/net"
9+
"github.com/hduhelp/hdu-cli/cmd/rpc"
610
"github.com/spf13/cobra"
711
"github.com/spf13/viper"
8-
"os"
912
)
1013

1114
// rootCmd represents the base command when called without any subcommands
@@ -39,7 +42,7 @@ func init() {
3942
rootCmd.PersistentFlags().BoolP("verbose", "V", false, "show more info")
4043
cobra.CheckErr(viper.BindPFlag("verbose", rootCmd.PersistentFlags().Lookup("verbose")))
4144

42-
rootCmd.AddCommand(net.Cmd)
45+
rootCmd.AddCommand(net.Cmd, auth.Cmd, rpc.Cmd)
4346
}
4447

4548
var cfgFile string

cmd/rpc/rpc.go

Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
package rpc
2+
3+
import (
4+
"context"
5+
"fmt"
6+
"reflect"
7+
"sort"
8+
9+
healthv1 "github.com/hduhelp/api_open_sdk/campusapis/health/v1"
10+
libraryv1 "github.com/hduhelp/api_open_sdk/campusapis/library/v1"
11+
schooltimev1 "github.com/hduhelp/api_open_sdk/campusapis/schoolTime/v1"
12+
staffv1 "github.com/hduhelp/api_open_sdk/campusapis/staff/v1"
13+
teachingv1 "github.com/hduhelp/api_open_sdk/campusapis/teaching/v1"
14+
authv1 "github.com/hduhelp/api_open_sdk/gatewayapis/auth/v1"
15+
grpcclient "github.com/hduhelp/api_open_sdk/grpcClient"
16+
"github.com/hduhelp/hdu-cli/pkg/table"
17+
"github.com/manifoldco/promptui"
18+
"github.com/samber/lo"
19+
"github.com/spf13/cobra"
20+
"github.com/spf13/viper"
21+
"google.golang.org/protobuf/types/known/emptypb"
22+
"gopkg.in/yaml.v2"
23+
)
24+
25+
var Cmd = &cobra.Command{
26+
Use: "rpc",
27+
}
28+
29+
func init() {
30+
Cmd.AddCommand(listCmd, runCmd)
31+
}
32+
33+
var listCmd = &cobra.Command{
34+
Use: "list",
35+
Run: func(cmd *cobra.Command, args []string) {
36+
listMethods()
37+
},
38+
}
39+
40+
var clients = make(map[string]any)
41+
42+
var methods = make(map[string][]string)
43+
44+
func registerClient(client any) {
45+
t := reflect.TypeOf(client)
46+
m := make([]string, 0)
47+
for i := 0; i < t.Out(0).NumMethod(); i++ {
48+
m = append(m, t.Out(0).Method(i).Name)
49+
}
50+
methods[t.Out(0).String()] = m
51+
}
52+
53+
var clientRegisters = []any{
54+
authv1.NewAuthServiceClient,
55+
staffv1.NewCampusServiceClient,
56+
teachingv1.NewTeachingServiceClient,
57+
healthv1.NewHealthServiceClient,
58+
schooltimev1.NewSchoolTimeServiceClient,
59+
libraryv1.NewLibraryServiceClient,
60+
}
61+
62+
func initMethods() {
63+
for _, client := range clientRegisters {
64+
registerClient(client)
65+
}
66+
}
67+
68+
func listMethods() {
69+
initMethods()
70+
printJson(methods)
71+
}
72+
73+
func printJson(in any) {
74+
b, _ := yaml.Marshal(in)
75+
fmt.Println(string(b))
76+
}
77+
78+
func newClient(service string) reflect.Value {
79+
conn := grpcclient.Conn(context.Background())
80+
for _, client := range clientRegisters {
81+
if reflect.TypeOf(client).Out(0).String() == service {
82+
f := reflect.ValueOf(client)
83+
resultValues := f.Call([]reflect.Value{reflect.ValueOf(conn)})
84+
return resultValues[0]
85+
}
86+
}
87+
return reflect.Value{}
88+
}
89+
90+
var runCmd = &cobra.Command{
91+
Use: "run",
92+
Run: func(cmd *cobra.Command, args []string) {
93+
initMethods()
94+
serviceList := lo.Keys(methods)
95+
sort.Strings(serviceList)
96+
prompt := promptui.Select{
97+
Label: "Select service",
98+
Items: serviceList,
99+
}
100+
_, service, err := prompt.Run()
101+
102+
if err != nil {
103+
fmt.Printf("Prompt failed %v\n", err)
104+
return
105+
}
106+
prompt = promptui.Select{
107+
Label: "Select method",
108+
Items: methods[service],
109+
}
110+
_, method, err := prompt.Run()
111+
fmt.Printf("You choose %s %s\n", service, method)
112+
client := newClient(service)
113+
methodF := client.MethodByName(method)
114+
req := methodF.Type().In(1)
115+
var reqValue reflect.Value
116+
if req.String() == reflect.TypeOf(&emptypb.Empty{}).String() {
117+
reqValue = reflect.ValueOf(&emptypb.Empty{})
118+
} else {
119+
reqValue = reflect.New(req.Elem())
120+
// fmt.Println("please input values as json")
121+
// reader := bufio.NewReader(os.Stdin)
122+
// text, _ := reader.ReadString('\n')
123+
// err = json.Unmarshal([]byte(text), reqValue.Interface())
124+
// if err != nil {
125+
// panic(err)
126+
// }
127+
}
128+
fmt.Println(reqValue)
129+
ctx := grpcclient.WithToken(context.Background(), viper.GetString("auth.token"))
130+
result := methodF.Call([]reflect.Value{
131+
reflect.ValueOf(ctx),
132+
reqValue,
133+
})
134+
table.PrintStruct(result[0].Interface())
135+
fmt.Println(result[1])
136+
},
137+
}

go.mod

Lines changed: 27 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,47 +1,65 @@
11
module github.com/hduhelp/hdu-cli
22

3-
go 1.17
3+
go 1.18
44

55
require (
66
github.com/gin-gonic/gin v1.7.7 // indirect
7-
github.com/hduhelp/api_open_sdk v0.0.0-20220228122811-1bfcd510f755
7+
github.com/hduhelp/api_open_sdk v0.0.0-20220427110722-33d902848349
88
github.com/parnurzeal/gorequest v0.2.16
99
)
1010

1111
require (
12+
github.com/manifoldco/promptui v0.9.0
1213
github.com/olekukonko/tablewriter v0.0.5
13-
github.com/spf13/cobra v1.3.0
14+
github.com/samber/lo v1.11.0
15+
github.com/spf13/cobra v1.4.0
1416
github.com/spf13/viper v1.10.1
17+
google.golang.org/grpc v1.46.0
18+
google.golang.org/protobuf v1.28.0
19+
gopkg.in/yaml.v2 v2.4.0
1520
)
1621

1722
require (
23+
github.com/benbjohnson/clock v1.3.0 // indirect
24+
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e // indirect
1825
github.com/fsnotify/fsnotify v1.5.1 // indirect
26+
github.com/gin-contrib/sse v0.1.0 // indirect
27+
github.com/go-playground/locales v0.14.0 // indirect
28+
github.com/go-playground/universal-translator v0.18.0 // indirect
29+
github.com/go-playground/validator/v10 v10.10.1 // indirect
1930
github.com/golang/protobuf v1.5.2 // indirect
20-
github.com/gopherjs/gopherjs v0.0.0-20211111143520-d0d5ecc1a356 // indirect
31+
github.com/grpc-ecosystem/grpc-gateway/v2 v2.10.0 // indirect
2132
github.com/hashicorp/hcl v1.0.0 // indirect
2233
github.com/inconshreveable/mousetrap v1.0.0 // indirect
2334
github.com/json-iterator/go v1.1.12 // indirect
2435
github.com/jtolds/gls v4.20.0+incompatible // indirect
36+
github.com/leodido/go-urn v1.2.1 // indirect
2537
github.com/magiconair/properties v1.8.6 // indirect
38+
github.com/mattn/go-isatty v0.0.14 // indirect
2639
github.com/mattn/go-runewidth v0.0.13 // indirect
2740
github.com/mitchellh/mapstructure v1.4.3 // indirect
2841
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
2942
github.com/modern-go/reflect2 v1.0.2 // indirect
3043
github.com/pelletier/go-toml v1.9.4 // indirect
3144
github.com/pkg/errors v0.9.1 // indirect
3245
github.com/rivo/uniseg v0.2.0 // indirect
33-
github.com/smartystreets/assertions v1.2.1 // indirect
3446
github.com/spf13/afero v1.8.1 // indirect
3547
github.com/spf13/cast v1.4.1 // indirect
3648
github.com/spf13/jwalterweatherman v1.1.0 // indirect
3749
github.com/spf13/pflag v1.0.5 // indirect
50+
github.com/stretchr/testify v1.7.1 // indirect
3851
github.com/subosito/gotenv v1.2.0 // indirect
3952
github.com/ugorji/go/codec v1.2.7 // indirect
40-
golang.org/x/net v0.0.0-20220225172249-27dd8689420f // indirect
41-
golang.org/x/sys v0.0.0-20220307203707-22a9840ba4d7 // indirect
53+
go.uber.org/atomic v1.9.0 // indirect
54+
go.uber.org/multierr v1.8.0 // indirect
55+
go.uber.org/zap v1.21.0 // indirect
56+
golang.org/x/crypto v0.0.0-20220331220935-ae2d96664a29 // indirect
57+
golang.org/x/exp v0.0.0-20220303212507-bbda1eaf7a17 // indirect
58+
golang.org/x/net v0.0.0-20220425223048-2871e0cb64e4 // indirect
59+
golang.org/x/sys v0.0.0-20220422013727-9388b58f7150 // indirect
4260
golang.org/x/text v0.3.7 // indirect
43-
google.golang.org/protobuf v1.27.1 // indirect
61+
golang.org/x/xerrors v0.0.0-20220411194840-2f41105eb62f // indirect
62+
google.golang.org/genproto v0.0.0-20220426171045-31bebdecfb46 // indirect
4463
gopkg.in/ini.v1 v1.66.4 // indirect
45-
gopkg.in/yaml.v2 v2.4.0 // indirect
4664
moul.io/http2curl v1.0.0 // indirect
4765
)

0 commit comments

Comments
 (0)