- Building Microservices with Go
- Nic Jackson
- 397字
- 2021-07-15 17:28:05
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.
- Unity 2020 By Example
- The Android Game Developer's Handbook
- Learning Elixir
- Java Web及其框架技術
- Java開發入行真功夫
- Swift 3 New Features
- Android Native Development Kit Cookbook
- 基于SpringBoot實現:Java分布式中間件開發入門與實戰
- HTML5開發精要與實例詳解
- 時空數據建模及其應用
- 自學Python:編程基礎、科學計算及數據分析(第2版)
- Go語言從入門到精通
- Python一行流:像專家一樣寫代碼
- Python預測分析與機器學習
- 3D Printing Designs:Octopus Pencil Holder