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

    评论

报告相同问题?

悬赏问题

  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试