hprose/hprose-golang

如何在OnBeforeInvoke中获取SocketContext?需要获取客户端的IP

lamjack opened this issue · 3 comments

...
func (e *ServerEvent) OnBeforeInvoke(name string, args []reflect.Value, byref bool, context rpc.Context) {
        // 这里如何获取IP?
	log.WithFields(logrus.Fields{
		"FuncName": name,
		"IP":       "",
	}).Info(args)
}

func main() {
	uri := "tcp4://127.0.0.1:10000"

	server := rpc.NewTCPServer(uri)
	server.AddFilter(StatFilter{"Server"})
	server.Event = &ServerEvent{}

	server.Start()
}
...

谢谢。

andot commented

直接对 context 做类型断言,就可以转换为 rpc.SocketContext 类型的对象,之后就可以获取到 IP 地址了。

...
func (e *ServerEvent) OnBeforeInvoke(name string, args []reflect.Value, byref bool, context rpc.Context) {
	sContext = context.(rpc.SocketContext)
	log.WithFields(logrus.Fields{
		"FuncName": name,
		"IP":       sContext.Conn.RemoteAddr().String(),
	}).Info(args)
}

2017-11-27 5 16 43

试过直接做类型断言了。

andot commented

需要断言为 (*rpc.SocketContext)