官术网_书友最值得收藏!

RPC over HTTP

In the instance that you need to use HTTP as your transport protocol then the rpc package can facilitate this by calling the HandleHTTP method.

The HandleHTTP method sets up two endpoints in your application:

const ( 
// Defaults used by HandleHTTP
DefaultRPCPath = "/_goRPC_"
DefaultDebugPath = "/debug/rpc"
)

If you point your browser at the DefaultDebugPath you can see details for the registered endpoints, there are two things to note:

  • This does not mean you can communicate easily with your API from a web browser. The messages are still gob encoded so you would need to write a gob encoder and decoder in JavaScript, which I am not actually sure is possible. It was certainly never the intent of the package to support this capability and therefore I would not advise this action, a JSON or JSON-RPC based message is much better suited to this use case.
  • The debug endpoint is not going to provide you with auto-generated documentation for your API. The output is fairly basic and the intention seems to be so you can track the number of calls made to an endpoint.

All that said there may be a reason why you need to use HTTP, possibly your network does not allow any other protocol or potentially you have a load balancer that is not capable of dealing with pure TCP connections. We can also take advantage of HTTP headers and other metadata which is not available using a pure TCP request.

rpc_http/server/server.go

22 func StartServer() { 
23 helloWorld := &HelloWorldHandler{}
24 rpc.Register(helloWorld)
25 rpc.HandleHTTP()
26
27 l, err := net.Listen("tcp", fmt.Sprintf(":%v", port))
28 if err != nil {
29 log.Fatal(fmt.Sprintf("Unable to listen on given port: %s", err))
30 }
31
32 log.Printf("Server starting on port %v\n", port)
33
34 http.Serve(l, nil)
35 }

If we look at line 25, in the preceding example, we can see we are calling the rpc.HandleHTTP method, this is a requirement using HTTP with RPC as it will register the HTTP handlers we mentioned earlier with the DefaultServer method. We then call the http.Serve method and pass it the listener we are creating in line 27, we are setting the second parameter to be nil as we wish to use the DefaultServer method. This is exactly the same method that we looked at in the previous examples when we were looking at RESTful endpoints.

主站蜘蛛池模板: 丹棱县| 秭归县| 融水| 安阳市| 仪征市| 扶沟县| 井冈山市| 清镇市| 普安县| 饶平县| 德庆县| 韶山市| 武胜县| 邵东县| 大港区| 若尔盖县| 富民县| 大冶市| 绍兴市| 舟曲县| 南澳县| 徐汇区| 察雅县| 嘉荫县| 娱乐| 咸丰县| 海淀区| 乐清市| 靖西县| 深水埗区| 元朗区| 乌审旗| 上栗县| 乐业县| 石嘴山市| 铅山县| 威海市| 柳州市| 石泉县| 甘德县| 六盘水市|