Skip to content

Instantly share code, notes, and snippets.

@n1try n1try/http_jsonrpc.go
Last active Aug 24, 2017

What would you like to do?
package main
import (
type RootNamespace struct{}
type RootNamespaceArgs struct {
Name string
type HttpConn struct {
in io.Reader
out io.Writer
func (c *HttpConn) Read(p []byte) (n int, err error) { return }
func (c *HttpConn) Write(d []byte) (n int, err error) { return c.out.Write(d) }
func (c *HttpConn) Close() error { return nil }
func (ns *RootNamespace) SayHello(args *RootNamespaceArgs, reply *string) error {
name := args.Name
*reply = string("Hello " + name)
return nil
func main() {
server := rpc.NewServer()
server.RegisterName("Root", &RootNamespace{})
server.HandleHTTP(rpc.DefaultRPCPath, rpc.DefaultDebugPath)
listener, e := net.Listen("tcp", ":3000")
if e != nil {
log.Fatal("Listen error:", e)
defer listener.Close()
http.Serve(listener, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/rpc" {
serverCodec := jsonrpc.NewServerCodec(&HttpConn{in: r.Body, out: w})
w.Header().Set("Content-type", "application/json")
err := server.ServeRequest(serverCodec)
if err != nil {
log.Printf("Error while serving JSON request: %v", err)
http.Error(w, "Error while serving JSON request, details have been logged.", 500)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.