hprose / hprose-golang

Hprose is a cross-language RPC. This project is Hprose for Golang.
MIT License
1.26k stars 205 forks source link

how do you pass the client's IP into the method of publishing? #67

Closed fromiuan closed 6 years ago

fromiuan commented 6 years ago

如何将将客户端的ip传入发布的方法中,

example

package main

import (
    "github.com/hprose/hprose-golang/rpc"
    "net/http"
)

type Member struct{}

type Login struct {
    Username string
    Password string
}

type LoginRsp struct {
    Status bool
    Token  string
}

func (m *Member) Login(req *Login, rsp *LoginRsp, context *rpc.HTTPContext) error {
    // How to get the client IP?
    return nil
}

func (m *Member) Regiest(req *Login, rsp *LoginRsp) error {
    // How to get the client IP?
    return nil
}

func main() {
    service := rpc.NewHTTPService()
    service.AddNetRPCMethods(new(Member))
    http.ListenAndServe(":8080", service)
}
andot commented 6 years ago
func (m *Member) Login(req *Login,rsp *LoginRsp, context *rpc.HTTPContext) error{
        ip := context.Request.RemoteAddr
    return nil
}

最后的参数,客户端调用时,不需要传入,服务器会自动传入。

fromiuan commented 6 years ago

When I add the context *rpc.HTTPContext, that Login function is not released 当我增加context *rpc.HTTPContext的时候,login方法没有被发布,但是我使用AddFunction发布的可以,结果如下

Fa3{u#s7"Regiest"s12"member_login"}z

package main

import (
    "fmt"
    "github.com/hprose/hprose-golang/rpc"
    "net/http"
)

type Member struct{}

type Login struct {
    Username string
    Password string
}

type LoginRsp struct {
    Status bool
    Token  string
}

func (m *Member) Login(req *Login, rsp *LoginRsp, context *rpc.HTTPContext) error {
    // How to get the client IP?
    return nil
}

func (m *Member) Regiest(req *Login, rsp *LoginRsp) error {
    // How to get the client IP?
    return nil
}

func MemberLogin(req *Login, context *rpc.HTTPContext) (rsp *LoginRsp) {
    fmt.Println(context.Request.RemoteAddr)
    return &LoginRsp{
        Status: true,
        Token:  "token",
    }
}

func main() {
    service := rpc.NewHTTPService()
    service.AddNetRPCMethods(new(Member))
    service.AddFunction("member_login", MemberLogin)
    http.ListenAndServe(":8080", service)
}
andot commented 6 years ago

你应该使用 AddInstanceMethodsAddAllMethods 这两个方法。AddNetRPCMethods 这个方法是用来发布为 net/rpc 编写的 RPC 服务的。你看一下文档就知道了。你用错了方法。

fromiuan commented 6 years ago

think小马哥耐心解答,点赞。