首页 > 解决方案 > 同时使用 HTTP 和 RPC

问题描述

我正在尝试在我的系统中实现rpchttp服务器。所以要同时监听服务器我已经运行了 2goroutines 这是一个代码

func main() {
    // Recovering all errors during the process
    defer errorHandler()

    wg.Add(2)

    go RPCConnect()

    fmt.Println("Listening for RPC   127.0.0.1:" + config.rpcPort)

    go HTTPConnect()

    fmt.Println("Listening for HTTP  127.0.0.1:" + config.httpPort)

    wg.Wait()
}


func RPCConnect() {
    err := rpc.Register(pool)

    if err != nil {
        panic(err)
    }

    rpc.HandleHTTP()

    listener, e := net.Listen("tcp", ":"+config.rpcPort)
    if e != nil {
        panic(e)
    }
    err = http.Serve(listener, nil)
    if err != nil {
        panic(err)
    }
}

func HTTPConnect() {

    var httpPool HTTPPool

    r := mux.NewRouter()
    r.HandleFunc("/create", httpPool.Create).Methods("POST")
    r.HandleFunc("/generate", httpPool.Generate).Methods("POST")
    r.HandleFunc("/list", httpPool.List).Methods("GET")
    r.HandleFunc("/delete", httpPool.Delete).Methods("POST")

    err := http.ListenAndServe("localhost:"+config.httpPort, r)

    if err != nil {
        panic(err)
    }

}

我不知道这是不是最好的方法。有人可以告诉我更简单灵活的方法吗?

如果问题不相关,我提前道歉

标签: httpgorpc

解决方案


建议的方法非常好。

如果您只想使用一个端口而不是两个端口,有几个第三方工具可以做到这一点:

1) https://github.com/soheilhy/cmux

2) https://github.com/grpc-ecosystem/grpc-gateway


推荐阅读