Last active
August 24, 2017 12:31
-
-
Save muety/fc525200d54e4e7c1c97d46575ffd93e to your computer and use it in GitHub Desktop.
Go JSON-RPC over HTTP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"io" | |
"log" | |
"net" | |
"net/http" | |
"net/rpc" | |
"net/rpc/jsonrpc" | |
) | |
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 c.in.Read(p) } | |
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") | |
w.WriteHeader(200) | |
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) | |
return | |
} | |
} | |
})) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment