Documentation
¶
Overview ¶
Package rpk provides simple RPC between Javascript and Go. The package converts objects to RPC handlers that call their exported methods.
Server code example ¶
The server defines the exported RPC interface through the methods of a type.
type myAPI struct{}
func (myAPI) Half(i int) int {
return i / 2
}
func main() {
http.HandleFunc("/api/rpk.js", rpk.HandleJS) // Serves client code.
handler, _ := rpk.HandlerFunc(myAPI{})
http.HandleFunc("/api", handler)
http.ListenAndServe(":8080", nil)
}
Client code example ¶
The client needs to fetch the complementary Javascript code.
<script type="text/javascript" src="/api/rpk.js"></script>
<script type="text/javascript">
let api = rpk("/api")
api.onReady(function(error) {...});
// ... After ready ...
api.Half(10, function(result, error) {
if (error) {
console.error("error=" + error);
} else {
console.log("10/2=" + result);
}
});
</script>
Restrictions on RPC methods ¶
The methods of an RPC object must: (1) have at most 1 input argument, which should be JSON encodable (2) have at most 2 outputs: 1 optional value of any JSON encodable type, and an optional error. If using 2 outputs, the error should come second.
Unexported methods are ignored and do not have any restriction.
Javascript API ¶
The Javascript code exposes a single function.
rpk(/*string*/ url)
Returns an RPK object, which will have the exported methods of the Go object that handles that URL.
rpkObject.ready
Boolean. Indicates whether this RPK object is ready to be called.
rpkObject.onReady( callback(error) )
Adds a listener that will be called when myRpkObject finishes initializing. If successful, error will be null. Else, error will be a string describing the problem. Several listeners can be added. They will be called by order of adding.
rpkObject.FuncName(param, callback(data, error))
Calls a Go method. Param should be of the type expected by the Go method. If the Go method expects no input, then param should be omitted. On success, error will be null and data will contain the output (if any). On error, error will be a string describing the problem.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func HandleJS ¶
func HandleJS(w http.ResponseWriter, r *http.Request)
HandleJS returns an http.HandlerFunc for serving the Javascript client code.
func HandlerFunc ¶
func HandlerFunc(a interface{}) (http.HandlerFunc, error)
HandlerFunc returns a handler function that calls a's exported methods. Access this handler using the Javascript code served by HandleJS. Returns an error if a's methods do not match the requirements - see package description.
Types ¶
This section is empty.