Skip to content

Commit

Permalink
optimize: add GetCallerIP util method in kitexutil
Browse files Browse the repository at this point in the history
  • Loading branch information
YangruiEmma committed Dec 6, 2023
1 parent 365c91a commit cfc92ea
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
20 changes: 20 additions & 0 deletions pkg/utils/kitexutil/kitexutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,26 @@ func GetCallerAddr(ctx context.Context) (net.Addr, bool) {
return ri.From().Address(), true
}

// GetCallerIP is used for the server to get the IP of the caller.
// Return false if failed to get the information.
func GetCallerIP(ctx context.Context) (string, bool) {
defer func() { recover() }()

ri := rpcinfo.GetRPCInfo(ctx)
if ri == nil {
return "", false
}
addrStr := ri.From().Address().String()
if len(addrStr) == 0 {
return "", false
}

if ip, _, err := net.SplitHostPort(addrStr); err == nil {
return ip, true
}
return addrStr, true
}

// GetTransportProtocol gets the transport protocol of the request.
// Return false if failed to get the information.
func GetTransportProtocol(ctx context.Context) (string, bool) {
Expand Down
27 changes: 27 additions & 0 deletions pkg/utils/kitexutil/kitexutil_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,33 @@ func TestGetCallerAddr(t *testing.T) {
}
}

func TestGetCallerIP(t *testing.T) {
type args struct {
ctx context.Context
}
tests := []struct {
name string
args args
want string
want1 bool
}{
{name: "Success", args: args{testCtx}, want: "127.0.0.1", want1: true},
{name: "Failure", args: args{context.Background()}, want: "", want1: false},
{name: "Panic recovered", args: args{panicCtx}, want: "", want1: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, got1 := GetCallerIP(tt.args.ctx)
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("GetCallerAddr() got = %v, want %v", got, tt.want)
}
if got1 != tt.want1 {
t.Errorf("GetCallerAddr() got1 = %v, want %v", got1, tt.want1)
}
})
}
}

func TestGetMethod(t *testing.T) {
type args struct {
ctx context.Context
Expand Down

0 comments on commit cfc92ea

Please sign in to comment.