Wiki

Clone wiki

http_jsonrpc.go / Home

http_jsonrpc.go

  • JSONRPC server usable with http package
  • Supports SMD - Service Mapping Descriptions
  • Nicer function syntax
  • MIT license

Example

package main

import (
	"bitbucket.org/taruti/http_jsonrpc.go"
	"http"
	"os"
	)

func add(a int, b int) int {
	return a+b
}
func negate(a int) (int,os.Error) {
	if a==0 { return 0,os.NewError("Zero!") }
	return -a,nil
}

func index(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte(`
<!DOCTYPE HTML>
<html>
<title>test</title>
<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.5/dojo/dojo.xd.js"
		djConfig="parseOnLoad: true, isDebug: true"
		type="text/javascript"></script>
<script type="text/javascript">
dojo.require('dojo.rpc.JsonService');
function setup() {
var smdURL = '/post';
srv = new dojo.rpc.JsonService(smdURL);
}

function doCalc() {
console.log(srv)
srv.add(document.getElementById('a').value, document.getElementById('b').value).addCallback(doCalcCallback);
srv.negate(document.getElementById('a').value).addCallback(doCalcCallback);
}

function doCalcCallback(result) {
alert(result);
}

dojo.addOnLoad(setup);
</script>
<body>

<fieldset>
  <legend>Simple JSON-RPC example</legend>
  A: <input type="text" id="a" size="3"/> B: <input type="text" id="b" size="3"/><br/>
  <input type="button" onclick="doCalc();" value="A+B"/>
</fieldset>

HTML from http://examples.stubbles.net/docroot/json-rpc/dojo.php
</body>
</html>
`))
}

func main() {
	s := http_jsonrpc.New()
	s.Register("add", add)
	s.Register("negate", negate)
	http.HandleFunc("/", index)
	http.Handle("/post", s)
	http.ListenAndServe(":8080", nil)
}

Updated