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

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.

主站蜘蛛池模板: 唐山市| 七台河市| 达尔| 平远县| 陕西省| 阳曲县| 苏尼特左旗| 永善县| 泸水县| 榕江县| 普宁市| 两当县| 呼和浩特市| 闻喜县| 平定县| 阳谷县| 南京市| 徐汇区| 新绛县| 措美县| 桃源县| 福州市| 定南县| 白城市| 正宁县| 西乌珠穆沁旗| 江华| 梧州市| 锡林浩特市| 镇坪县| 庆元县| 莫力| 莆田市| 宁南县| 普兰店市| 湄潭县| 恭城| 莒南县| 景泰县| 淮阳县| 自贡市|