summaryrefslogtreecommitdiff
path: root/devdocs/go/net%2Frpc%2Findex.html
blob: b70617b55b096c0bdf153271fe165e62c8824ad5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
<h1> Package rpc  </h1>     <ul id="short-nav">
<li><code>import "net/rpc"</code></li>
<li><a href="#pkg-overview" class="overviewLink">Overview</a></li>
<li><a href="#pkg-index" class="indexLink">Index</a></li>
<li><a href="#pkg-subdirectories">Subdirectories</a></li>
</ul>     <h2 id="pkg-overview">Overview </h2> <p>Package rpc provides access to the exported methods of an object across a network or other I/O connection. A server registers an object, making it visible as a service with the name of the type of the object. After registration, exported methods of the object will be accessible remotely. A server may register multiple objects (services) of different types but it is an error to register multiple objects of the same type. </p>
<p>Only methods that satisfy these criteria will be made available for remote access; other methods will be ignored: </p>
<ul> <li>the method's type is exported. </li>
<li>the method is exported. </li>
<li>the method has two arguments, both exported (or builtin) types. </li>
<li>the method's second argument is a pointer. </li>
<li>the method has return type error. </li>
</ul> <p>In effect, the method must look schematically like </p>
<pre data-language="go">func (t *T) MethodName(argType T1, replyType *T2) error
</pre> <p>where T1 and T2 can be marshaled by encoding/gob. These requirements apply even if a different codec is used. (In the future, these requirements may soften for custom codecs.) </p>
<p>The method's first argument represents the arguments provided by the caller; the second argument represents the result parameters to be returned to the caller. The method's return value, if non-nil, is passed back as a string that the client sees as if created by <span>errors.New</span>. If an error is returned, the reply parameter will not be sent back to the client. </p>
<p>The server may handle requests on a single connection by calling <a href="#ServeConn">ServeConn</a>. More typically it will create a network listener and call <a href="#Accept">Accept</a> or, for an HTTP listener, <a href="#HandleHTTP">HandleHTTP</a> and <span>http.Serve</span>. </p>
<p>A client wishing to use the service establishes a connection and then invokes <a href="#NewClient">NewClient</a> on the connection. The convenience function <a href="#Dial">Dial</a> (<a href="#DialHTTP">DialHTTP</a>) performs both steps for a raw network connection (an HTTP connection). The resulting <a href="#Client">Client</a> object has two methods, <a href="#Call">Call</a> and Go, that specify the service and method to call, a pointer containing the arguments, and a pointer to receive the result parameters. </p>
<p>The Call method waits for the remote call to complete while the Go method launches the call asynchronously and signals completion using the Call structure's Done channel. </p>
<p>Unless an explicit codec is set up, package <span>encoding/gob</span> is used to transport the data. </p>
<p>Here is a simple example. A server wishes to export an object of type Arith: </p>
<pre data-language="go">package server

import "errors"

type Args struct {
	A, B int
}

type Quotient struct {
	Quo, Rem int
}

type Arith int

func (t *Arith) Multiply(args *Args, reply *int) error {
	*reply = args.A * args.B
	return nil
}

func (t *Arith) Divide(args *Args, quo *Quotient) error {
	if args.B == 0 {
		return errors.New("divide by zero")
	}
	quo.Quo = args.A / args.B
	quo.Rem = args.A % args.B
	return nil
}
</pre> <p>The server calls (for HTTP service): </p>
<pre data-language="go">arith := new(Arith)
rpc.Register(arith)
rpc.HandleHTTP()
l, err := net.Listen("tcp", ":1234")
if err != nil {
	log.Fatal("listen error:", err)
}
go http.Serve(l, nil)
</pre> <p>At this point, clients can see a service "Arith" with methods "Arith.Multiply" and "Arith.Divide". To invoke one, a client first dials the server: </p>
<pre data-language="go">client, err := rpc.DialHTTP("tcp", serverAddress + ":1234")
if err != nil {
	log.Fatal("dialing:", err)
}
</pre> <p>Then it can make a remote call: </p>
<pre data-language="go">// Synchronous call
args := &amp;server.Args{7,8}
var reply int
err = client.Call("Arith.Multiply", args, &amp;reply)
if err != nil {
	log.Fatal("arith error:", err)
}
fmt.Printf("Arith: %d*%d=%d", args.A, args.B, reply)
</pre> <p>or </p>
<pre data-language="go">// Asynchronous call
quotient := new(Quotient)
divCall := client.Go("Arith.Divide", args, quotient, nil)
replyCall := &lt;-divCall.Done	// will be equal to divCall
// check errors, print, etc.
</pre> <p>A server implementation will often provide a simple, type-safe wrapper for the client. </p>
<p>The net/rpc package is frozen and is not accepting new features. </p>     <h2 id="pkg-index">Index </h2>  <ul id="manual-nav">
<li><a href="#pkg-constants">Constants</a></li>
<li><a href="#pkg-variables">Variables</a></li>
<li><a href="#Accept">func Accept(lis net.Listener)</a></li>
<li><a href="#HandleHTTP">func HandleHTTP()</a></li>
<li><a href="#Register">func Register(rcvr any) error</a></li>
<li><a href="#RegisterName">func RegisterName(name string, rcvr any) error</a></li>
<li><a href="#ServeCodec">func ServeCodec(codec ServerCodec)</a></li>
<li><a href="#ServeConn">func ServeConn(conn io.ReadWriteCloser)</a></li>
<li><a href="#ServeRequest">func ServeRequest(codec ServerCodec) error</a></li>
<li><a href="#Call">type Call</a></li>
<li><a href="#Client">type Client</a></li>
<li> <a href="#Dial">func Dial(network, address string) (*Client, error)</a>
</li>
<li> <a href="#DialHTTP">func DialHTTP(network, address string) (*Client, error)</a>
</li>
<li> <a href="#DialHTTPPath">func DialHTTPPath(network, address, path string) (*Client, error)</a>
</li>
<li> <a href="#NewClient">func NewClient(conn io.ReadWriteCloser) *Client</a>
</li>
<li> <a href="#NewClientWithCodec">func NewClientWithCodec(codec ClientCodec) *Client</a>
</li>
<li> <a href="#Client.Call">func (client *Client) Call(serviceMethod string, args any, reply any) error</a>
</li>
<li> <a href="#Client.Close">func (client *Client) Close() error</a>
</li>
<li> <a href="#Client.Go">func (client *Client) Go(serviceMethod string, args any, reply any, done chan *Call) *Call</a>
</li>
<li><a href="#ClientCodec">type ClientCodec</a></li>
<li><a href="#Request">type Request</a></li>
<li><a href="#Response">type Response</a></li>
<li><a href="#Server">type Server</a></li>
<li> <a href="#NewServer">func NewServer() *Server</a>
</li>
<li> <a href="#Server.Accept">func (server *Server) Accept(lis net.Listener)</a>
</li>
<li> <a href="#Server.HandleHTTP">func (server *Server) HandleHTTP(rpcPath, debugPath string)</a>
</li>
<li> <a href="#Server.Register">func (server *Server) Register(rcvr any) error</a>
</li>
<li> <a href="#Server.RegisterName">func (server *Server) RegisterName(name string, rcvr any) error</a>
</li>
<li> <a href="#Server.ServeCodec">func (server *Server) ServeCodec(codec ServerCodec)</a>
</li>
<li> <a href="#Server.ServeConn">func (server *Server) ServeConn(conn io.ReadWriteCloser)</a>
</li>
<li> <a href="#Server.ServeHTTP">func (server *Server) ServeHTTP(w http.ResponseWriter, req *http.Request)</a>
</li>
<li> <a href="#Server.ServeRequest">func (server *Server) ServeRequest(codec ServerCodec) error</a>
</li>
<li><a href="#ServerCodec">type ServerCodec</a></li>
<li><a href="#ServerError">type ServerError</a></li>
<li> <a href="#ServerError.Error">func (e ServerError) Error() string</a>
</li>
</ul> <h3>Package files</h3> <p>  <span>client.go</span> <span>debug.go</span> <span>server.go</span>  </p>   <h2 id="pkg-constants">Constants</h2> <pre data-language="go">const (
    // Defaults used by HandleHTTP
    DefaultRPCPath   = "/_goRPC_"
    DefaultDebugPath = "/debug/rpc"
)</pre> <h2 id="pkg-variables">Variables</h2> <p>DefaultServer is the default instance of <a href="#Server">*Server</a>. </p>
<pre data-language="go">var DefaultServer = NewServer()</pre> <pre data-language="go">var ErrShutdown = errors.New("connection is shut down")</pre> <h2 id="Accept">func <span>Accept</span>  </h2> <pre data-language="go">func Accept(lis net.Listener)</pre> <p>Accept accepts connections on the listener and serves requests to <a href="#DefaultServer">DefaultServer</a> for each incoming connection. Accept blocks; the caller typically invokes it in a go statement. </p>
<h2 id="HandleHTTP">func <span>HandleHTTP</span>  </h2> <pre data-language="go">func HandleHTTP()</pre> <p>HandleHTTP registers an HTTP handler for RPC messages to <a href="#DefaultServer">DefaultServer</a> on <a href="#DefaultRPCPath">DefaultRPCPath</a> and a debugging handler on <a href="#DefaultDebugPath">DefaultDebugPath</a>. It is still necessary to invoke <span>http.Serve</span>(), typically in a go statement. </p>
<h2 id="Register">func <span>Register</span>  </h2> <pre data-language="go">func Register(rcvr any) error</pre> <p>Register publishes the receiver's methods in the <a href="#DefaultServer">DefaultServer</a>. </p>
<h2 id="RegisterName">func <span>RegisterName</span>  </h2> <pre data-language="go">func RegisterName(name string, rcvr any) error</pre> <p>RegisterName is like <a href="#Register">Register</a> but uses the provided name for the type instead of the receiver's concrete type. </p>
<h2 id="ServeCodec">func <span>ServeCodec</span>  </h2> <pre data-language="go">func ServeCodec(codec ServerCodec)</pre> <p>ServeCodec is like <a href="#ServeConn">ServeConn</a> but uses the specified codec to decode requests and encode responses. </p>
<h2 id="ServeConn">func <span>ServeConn</span>  </h2> <pre data-language="go">func ServeConn(conn io.ReadWriteCloser)</pre> <p>ServeConn runs the <a href="#DefaultServer">DefaultServer</a> on a single connection. ServeConn blocks, serving the connection until the client hangs up. The caller typically invokes ServeConn in a go statement. ServeConn uses the gob wire format (see package gob) on the connection. To use an alternate codec, use <a href="#ServeCodec">ServeCodec</a>. See <a href="#NewClient">NewClient</a>'s comment for information about concurrent access. </p>
<h2 id="ServeRequest">func <span>ServeRequest</span>  </h2> <pre data-language="go">func ServeRequest(codec ServerCodec) error</pre> <p>ServeRequest is like <a href="#ServeCodec">ServeCodec</a> but synchronously serves a single request. It does not close the codec upon completion. </p>
<h2 id="Call">type <span>Call</span>  </h2> <p>Call represents an active RPC. </p>
<pre data-language="go">type Call struct {
    ServiceMethod string     // The name of the service and method to call.
    Args          any        // The argument to the function (*struct).
    Reply         any        // The reply from the function (*struct).
    Error         error      // After completion, the error status.
    Done          chan *Call // Receives *Call when Go is complete.
}
</pre> <h2 id="Client">type <span>Client</span>  </h2> <p>Client represents an RPC Client. There may be multiple outstanding Calls associated with a single Client, and a Client may be used by multiple goroutines simultaneously. </p>
<pre data-language="go">type Client struct {
    // contains filtered or unexported fields
}
</pre> <h3 id="Dial">func <span>Dial</span>  </h3> <pre data-language="go">func Dial(network, address string) (*Client, error)</pre> <p>Dial connects to an RPC server at the specified network address. </p>
<h3 id="DialHTTP">func <span>DialHTTP</span>  </h3> <pre data-language="go">func DialHTTP(network, address string) (*Client, error)</pre> <p>DialHTTP connects to an HTTP RPC server at the specified network address listening on the default HTTP RPC path. </p>
<h3 id="DialHTTPPath">func <span>DialHTTPPath</span>  </h3> <pre data-language="go">func DialHTTPPath(network, address, path string) (*Client, error)</pre> <p>DialHTTPPath connects to an HTTP RPC server at the specified network address and path. </p>
<h3 id="NewClient">func <span>NewClient</span>  </h3> <pre data-language="go">func NewClient(conn io.ReadWriteCloser) *Client</pre> <p>NewClient returns a new <a href="#Client">Client</a> to handle requests to the set of services at the other end of the connection. It adds a buffer to the write side of the connection so the header and payload are sent as a unit. </p>
<p>The read and write halves of the connection are serialized independently, so no interlocking is required. However each half may be accessed concurrently so the implementation of conn should protect against concurrent reads or concurrent writes. </p>
<h3 id="NewClientWithCodec">func <span>NewClientWithCodec</span>  </h3> <pre data-language="go">func NewClientWithCodec(codec ClientCodec) *Client</pre> <p>NewClientWithCodec is like <a href="#NewClient">NewClient</a> but uses the specified codec to encode requests and decode responses. </p>
<h3 id="Client.Call">func (*Client) <span>Call</span>  </h3> <pre data-language="go">func (client *Client) Call(serviceMethod string, args any, reply any) error</pre> <p>Call invokes the named function, waits for it to complete, and returns its error status. </p>
<h3 id="Client.Close">func (*Client) <span>Close</span>  </h3> <pre data-language="go">func (client *Client) Close() error</pre> <p>Close calls the underlying codec's Close method. If the connection is already shutting down, <a href="#ErrShutdown">ErrShutdown</a> is returned. </p>
<h3 id="Client.Go">func (*Client) <span>Go</span>  </h3> <pre data-language="go">func (client *Client) Go(serviceMethod string, args any, reply any, done chan *Call) *Call</pre> <p>Go invokes the function asynchronously. It returns the <a href="#Call">Call</a> structure representing the invocation. The done channel will signal when the call is complete by returning the same Call object. If done is nil, Go will allocate a new channel. If non-nil, done must be buffered or Go will deliberately crash. </p>
<h2 id="ClientCodec">type <span>ClientCodec</span>  </h2> <p>A ClientCodec implements writing of RPC requests and reading of RPC responses for the client side of an RPC session. The client calls [ClientCodec.WriteRequest] to write a request to the connection and calls [ClientCodec.ReadResponseHeader] and [ClientCodec.ReadResponseBody] in pairs to read responses. The client calls [ClientCodec.Close] when finished with the connection. ReadResponseBody may be called with a nil argument to force the body of the response to be read and then discarded. See <a href="#NewClient">NewClient</a>'s comment for information about concurrent access. </p>
<pre data-language="go">type ClientCodec interface {
    WriteRequest(*Request, any) error
    ReadResponseHeader(*Response) error
    ReadResponseBody(any) error

    Close() error
}</pre> <h2 id="Request">type <span>Request</span>  </h2> <p>Request is a header written before every RPC call. It is used internally but documented here as an aid to debugging, such as when analyzing network traffic. </p>
<pre data-language="go">type Request struct {
    ServiceMethod string // format: "Service.Method"
    Seq           uint64 // sequence number chosen by client
    // contains filtered or unexported fields
}
</pre> <h2 id="Response">type <span>Response</span>  </h2> <p>Response is a header written before every RPC return. It is used internally but documented here as an aid to debugging, such as when analyzing network traffic. </p>
<pre data-language="go">type Response struct {
    ServiceMethod string // echoes that of the Request
    Seq           uint64 // echoes that of the request
    Error         string // error, if any.
    // contains filtered or unexported fields
}
</pre> <h2 id="Server">type <span>Server</span>  </h2> <p>Server represents an RPC Server. </p>
<pre data-language="go">type Server struct {
    // contains filtered or unexported fields
}
</pre> <h3 id="NewServer">func <span>NewServer</span>  </h3> <pre data-language="go">func NewServer() *Server</pre> <p>NewServer returns a new <a href="#Server">Server</a>. </p>
<h3 id="Server.Accept">func (*Server) <span>Accept</span>  </h3> <pre data-language="go">func (server *Server) Accept(lis net.Listener)</pre> <p>Accept accepts connections on the listener and serves requests for each incoming connection. Accept blocks until the listener returns a non-nil error. The caller typically invokes Accept in a go statement. </p>
<h3 id="Server.HandleHTTP">func (*Server) <span>HandleHTTP</span>  </h3> <pre data-language="go">func (server *Server) HandleHTTP(rpcPath, debugPath string)</pre> <p>HandleHTTP registers an HTTP handler for RPC messages on rpcPath, and a debugging handler on debugPath. It is still necessary to invoke <span>http.Serve</span>(), typically in a go statement. </p>
<h3 id="Server.Register">func (*Server) <span>Register</span>  </h3> <pre data-language="go">func (server *Server) Register(rcvr any) error</pre> <p>Register publishes in the server the set of methods of the receiver value that satisfy the following conditions: </p>
<ul> <li>exported method of exported type </li>
<li>two arguments, both of exported type </li>
<li>the second argument is a pointer </li>
<li>one return value, of type error </li>
</ul> <p>It returns an error if the receiver is not an exported type or has no suitable methods. It also logs the error using package log. The client accesses each method using a string of the form "Type.Method", where Type is the receiver's concrete type. </p>
<h3 id="Server.RegisterName">func (*Server) <span>RegisterName</span>  </h3> <pre data-language="go">func (server *Server) RegisterName(name string, rcvr any) error</pre> <p>RegisterName is like <a href="#Register">Register</a> but uses the provided name for the type instead of the receiver's concrete type. </p>
<h3 id="Server.ServeCodec">func (*Server) <span>ServeCodec</span>  </h3> <pre data-language="go">func (server *Server) ServeCodec(codec ServerCodec)</pre> <p>ServeCodec is like <a href="#ServeConn">ServeConn</a> but uses the specified codec to decode requests and encode responses. </p>
<h3 id="Server.ServeConn">func (*Server) <span>ServeConn</span>  </h3> <pre data-language="go">func (server *Server) ServeConn(conn io.ReadWriteCloser)</pre> <p>ServeConn runs the server on a single connection. ServeConn blocks, serving the connection until the client hangs up. The caller typically invokes ServeConn in a go statement. ServeConn uses the gob wire format (see package gob) on the connection. To use an alternate codec, use <a href="#ServeCodec">ServeCodec</a>. See <a href="#NewClient">NewClient</a>'s comment for information about concurrent access. </p>
<h3 id="Server.ServeHTTP">func (*Server) <span>ServeHTTP</span>  </h3> <pre data-language="go">func (server *Server) ServeHTTP(w http.ResponseWriter, req *http.Request)</pre> <p>ServeHTTP implements an <span>http.Handler</span> that answers RPC requests. </p>
<h3 id="Server.ServeRequest">func (*Server) <span>ServeRequest</span>  </h3> <pre data-language="go">func (server *Server) ServeRequest(codec ServerCodec) error</pre> <p>ServeRequest is like <a href="#ServeCodec">ServeCodec</a> but synchronously serves a single request. It does not close the codec upon completion. </p>
<h2 id="ServerCodec">type <span>ServerCodec</span>  </h2> <p>A ServerCodec implements reading of RPC requests and writing of RPC responses for the server side of an RPC session. The server calls [ServerCodec.ReadRequestHeader] and [ServerCodec.ReadRequestBody] in pairs to read requests from the connection, and it calls [ServerCodec.WriteResponse] to write a response back. The server calls [ServerCodec.Close] when finished with the connection. ReadRequestBody may be called with a nil argument to force the body of the request to be read and discarded. See <a href="#NewClient">NewClient</a>'s comment for information about concurrent access. </p>
<pre data-language="go">type ServerCodec interface {
    ReadRequestHeader(*Request) error
    ReadRequestBody(any) error
    WriteResponse(*Response, any) error

    // Close can be called multiple times and must be idempotent.
    Close() error
}</pre> <h2 id="ServerError">type <span>ServerError</span>  </h2> <p>ServerError represents an error that has been returned from the remote side of the RPC connection. </p>
<pre data-language="go">type ServerError string</pre> <h3 id="ServerError.Error">func (ServerError) <span>Error</span>  </h3> <pre data-language="go">func (e ServerError) Error() string</pre> <h2 id="pkg-subdirectories">Subdirectories</h2> <div class="pkg-dir"> <table> <tr> <th class="pkg-name">Name</th> <th class="pkg-synopsis">Synopsis</th> </tr> <tr> <td colspan="2"><a href="../index">..</a></td> </tr> <tr> <td class="pkg-name"> <a href="jsonrpc/index">jsonrpc</a> </td> <td class="pkg-synopsis"> Package jsonrpc implements a JSON-RPC 1.0 ClientCodec and ServerCodec for the rpc package. </td> </tr> </table> </div><div class="_attribution">
  <p class="_attribution-p">
    &copy; Google, Inc.<br>Licensed under the Creative Commons Attribution License 3.0.<br>
    <a href="http://golang.org/pkg/net/rpc/" class="_attribution-link">http://golang.org/pkg/net/rpc/</a>
  </p>
</div>