Skip to content

Commit

Permalink
feat(grpc): grpc call
Browse files Browse the repository at this point in the history
  • Loading branch information
fdkevin0 committed Apr 27, 2022
1 parent 80f0c3e commit eda7e25
Show file tree
Hide file tree
Showing 7 changed files with 352 additions and 370 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/go.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ jobs:
runs-on: ubuntu-latest
steps:

- name: load Go 1.17 env
- name: load Go 1.18 env
uses: actions/setup-go@v3
with:
go-version: 1.17
go-version: 1.18
id: go

- name: checkout
Expand Down
100 changes: 100 additions & 0 deletions cmd/auth/auth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
package auth

import (
"context"
"fmt"
"log"
"net"
"net/http"
"net/url"
"time"

authv1 "github.com/hduhelp/api_open_sdk/gatewayapis/auth/v1"
grpcclient "github.com/hduhelp/api_open_sdk/grpcClient"
"github.com/hduhelp/hdu-cli/pkg/table"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"google.golang.org/protobuf/types/known/emptypb"
)

var Cmd = &cobra.Command{
Use: "auth",
}

func init() {
Cmd.AddCommand(loginCmd, logoutCmd, infoCmd)

loginCmd.Flags().StringP("token", "t", "", "hduhelp token")
}

var loginCmd = &cobra.Command{
Use: "login",
Run: func(cmd *cobra.Command, args []string) {
ctx := context.Background()
argToken := cmd.Flags().Lookup("token").Value.String()
if argToken != "" {
tokenVerify(ctx, argToken)
return
}
ln, err := net.Listen("tcp", ":11328")
if err != nil {
log.Fatalln(err)
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
token := r.URL.Query().Get("auth")
w.Write([]byte("login success, now return to cli"))
tokenVerify(ctx, token)
go func() {
time.Sleep(time.Second)
ln.Close()
}()
})
loginUrl, _ := url.Parse("https://api.hduhelp.com/login/auto")
loginUrl.RawQuery = url.Values{
"clientID": {"dashboard"},
"redirect": {"http://localhost:11328"},
}.Encode()
fmt.Println(loginUrl)
http.Serve(ln, http.DefaultServeMux)
},
}

func tokenVerify(ctx context.Context, token string) {
client := authv1.NewAuthServiceClient(grpcclient.Conn(ctx))
info, err := client.GetTokenInfo(grpcclient.WithToken(ctx, token), &emptypb.Empty{})
if err != nil {
log.Fatalln(err)
}
table.PrintStruct(info)
viper.Set("auth.token", token)
err = viper.WriteConfig()
cobra.CheckErr(err)
}

var logoutCmd = &cobra.Command{
Use: "logout",
Run: func(cmd *cobra.Command, args []string) {
viper.Set("auth.token", "")
err := viper.WriteConfig()
cobra.CheckErr(err)
fmt.Println("logout success")
},
}

var infoCmd = &cobra.Command{
Use: "info",
Run: func(cmd *cobra.Command, args []string) {
ctx := context.Background()
token := viper.GetString("auth.token")
if token == "" {
log.Fatalf("auth token not found")
}
client := authv1.NewAuthServiceClient(grpcclient.Conn(ctx))
info, err := client.GetTokenInfo(grpcclient.WithToken(ctx, token), &emptypb.Empty{})
if err != nil {
fmt.Println(err)
} else {
table.PrintStruct(info)
}
},
}
7 changes: 5 additions & 2 deletions cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,13 @@ package cmd

import (
"fmt"
"os"

"github.com/hduhelp/hdu-cli/cmd/auth"
"github.com/hduhelp/hdu-cli/cmd/net"
"github.com/hduhelp/hdu-cli/cmd/rpc"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"os"
)

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

rootCmd.AddCommand(net.Cmd)
rootCmd.AddCommand(net.Cmd, auth.Cmd, rpc.Cmd)
}

var cfgFile string
Expand Down
137 changes: 137 additions & 0 deletions cmd/rpc/rpc.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
package rpc

import (
"context"
"fmt"
"reflect"
"sort"

healthv1 "github.com/hduhelp/api_open_sdk/campusapis/health/v1"
libraryv1 "github.com/hduhelp/api_open_sdk/campusapis/library/v1"
schooltimev1 "github.com/hduhelp/api_open_sdk/campusapis/schoolTime/v1"
staffv1 "github.com/hduhelp/api_open_sdk/campusapis/staff/v1"
teachingv1 "github.com/hduhelp/api_open_sdk/campusapis/teaching/v1"
authv1 "github.com/hduhelp/api_open_sdk/gatewayapis/auth/v1"
grpcclient "github.com/hduhelp/api_open_sdk/grpcClient"
"github.com/hduhelp/hdu-cli/pkg/table"
"github.com/manifoldco/promptui"
"github.com/samber/lo"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"google.golang.org/protobuf/types/known/emptypb"
"gopkg.in/yaml.v2"
)

var Cmd = &cobra.Command{
Use: "rpc",
}

func init() {
Cmd.AddCommand(listCmd, runCmd)
}

var listCmd = &cobra.Command{
Use: "list",
Run: func(cmd *cobra.Command, args []string) {
listMethods()
},
}

var clients = make(map[string]any)

var methods = make(map[string][]string)

func registerClient(client any) {
t := reflect.TypeOf(client)
m := make([]string, 0)
for i := 0; i < t.Out(0).NumMethod(); i++ {
m = append(m, t.Out(0).Method(i).Name)
}
methods[t.Out(0).String()] = m
}

var clientRegisters = []any{
authv1.NewAuthServiceClient,
staffv1.NewCampusServiceClient,
teachingv1.NewTeachingServiceClient,
healthv1.NewHealthServiceClient,
schooltimev1.NewSchoolTimeServiceClient,
libraryv1.NewLibraryServiceClient,
}

func initMethods() {
for _, client := range clientRegisters {
registerClient(client)
}
}

func listMethods() {
initMethods()
printJson(methods)
}

func printJson(in any) {
b, _ := yaml.Marshal(in)
fmt.Println(string(b))
}

func newClient(service string) reflect.Value {
conn := grpcclient.Conn(context.Background())
for _, client := range clientRegisters {
if reflect.TypeOf(client).Out(0).String() == service {
f := reflect.ValueOf(client)
resultValues := f.Call([]reflect.Value{reflect.ValueOf(conn)})
return resultValues[0]
}
}
return reflect.Value{}
}

var runCmd = &cobra.Command{
Use: "run",
Run: func(cmd *cobra.Command, args []string) {
initMethods()
serviceList := lo.Keys(methods)
sort.Strings(serviceList)
prompt := promptui.Select{
Label: "Select service",
Items: serviceList,
}
_, service, err := prompt.Run()

if err != nil {
fmt.Printf("Prompt failed %v\n", err)
return
}
prompt = promptui.Select{
Label: "Select method",
Items: methods[service],
}
_, method, err := prompt.Run()
fmt.Printf("You choose %s %s\n", service, method)
client := newClient(service)
methodF := client.MethodByName(method)
req := methodF.Type().In(1)
var reqValue reflect.Value
if req.String() == reflect.TypeOf(&emptypb.Empty{}).String() {
reqValue = reflect.ValueOf(&emptypb.Empty{})
} else {
reqValue = reflect.New(req.Elem())
// fmt.Println("please input values as json")
// reader := bufio.NewReader(os.Stdin)
// text, _ := reader.ReadString('\n')
// err = json.Unmarshal([]byte(text), reqValue.Interface())
// if err != nil {
// panic(err)
// }
}
fmt.Println(reqValue)
ctx := grpcclient.WithToken(context.Background(), viper.GetString("auth.token"))
result := methodF.Call([]reflect.Value{
reflect.ValueOf(ctx),
reqValue,
})
table.PrintStruct(result[0].Interface())
fmt.Println(result[1])
},
}
36 changes: 27 additions & 9 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,47 +1,65 @@
module github.com/hduhelp/hdu-cli

go 1.17
go 1.18

require (
github.com/gin-gonic/gin v1.7.7 // indirect
github.com/hduhelp/api_open_sdk v0.0.0-20220228122811-1bfcd510f755
github.com/hduhelp/api_open_sdk v0.0.0-20220427110722-33d902848349
github.com/parnurzeal/gorequest v0.2.16
)

require (
github.com/manifoldco/promptui v0.9.0
github.com/olekukonko/tablewriter v0.0.5
github.com/spf13/cobra v1.3.0
github.com/samber/lo v1.11.0
github.com/spf13/cobra v1.4.0
github.com/spf13/viper v1.10.1
google.golang.org/grpc v1.46.0
google.golang.org/protobuf v1.28.0
gopkg.in/yaml.v2 v2.4.0
)

require (
github.com/benbjohnson/clock v1.3.0 // indirect
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e // indirect
github.com/fsnotify/fsnotify v1.5.1 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/go-playground/locales v0.14.0 // indirect
github.com/go-playground/universal-translator v0.18.0 // indirect
github.com/go-playground/validator/v10 v10.10.1 // indirect
github.com/golang/protobuf v1.5.2 // indirect
github.com/gopherjs/gopherjs v0.0.0-20211111143520-d0d5ecc1a356 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.10.0 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/inconshreveable/mousetrap v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/jtolds/gls v4.20.0+incompatible // indirect
github.com/leodido/go-urn v1.2.1 // indirect
github.com/magiconair/properties v1.8.6 // indirect
github.com/mattn/go-isatty v0.0.14 // indirect
github.com/mattn/go-runewidth v0.0.13 // indirect
github.com/mitchellh/mapstructure v1.4.3 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml v1.9.4 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/rivo/uniseg v0.2.0 // indirect
github.com/smartystreets/assertions v1.2.1 // indirect
github.com/spf13/afero v1.8.1 // indirect
github.com/spf13/cast v1.4.1 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/stretchr/testify v1.7.1 // indirect
github.com/subosito/gotenv v1.2.0 // indirect
github.com/ugorji/go/codec v1.2.7 // indirect
golang.org/x/net v0.0.0-20220225172249-27dd8689420f // indirect
golang.org/x/sys v0.0.0-20220307203707-22a9840ba4d7 // indirect
go.uber.org/atomic v1.9.0 // indirect
go.uber.org/multierr v1.8.0 // indirect
go.uber.org/zap v1.21.0 // indirect
golang.org/x/crypto v0.0.0-20220331220935-ae2d96664a29 // indirect
golang.org/x/exp v0.0.0-20220303212507-bbda1eaf7a17 // indirect
golang.org/x/net v0.0.0-20220425223048-2871e0cb64e4 // indirect
golang.org/x/sys v0.0.0-20220422013727-9388b58f7150 // indirect
golang.org/x/text v0.3.7 // indirect
google.golang.org/protobuf v1.27.1 // indirect
golang.org/x/xerrors v0.0.0-20220411194840-2f41105eb62f // indirect
google.golang.org/genproto v0.0.0-20220426171045-31bebdecfb46 // indirect
gopkg.in/ini.v1 v1.66.4 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
moul.io/http2curl v1.0.0 // indirect
)
Loading

0 comments on commit eda7e25

Please sign in to comment.