dongpiao9078 2019-01-24 11:17
浏览 324

同时使用HTTP和RPC

I am trying to implement rpc and http server in my system. So to listen servers at the same time I have run 2 goroutines Here is a code

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)
    }

}

I dont know is this a best way or not . Can somebody tell me more simple and flexible method?

I apologize in advance if the question is not relevant

  • 写回答

1条回答 默认 最新

  • dtbam62840 2019-01-24 12:30
    关注

    Suggested approach is pretty well.

    If you want to use only one port instead of two, there are several third-party tools to do it:

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

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

    评论

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集