Browse Source

Example 3: JSON-RPC 1

Frederic G. MARAND 9 years ago
parent
commit
c894f4a9b2
1 changed files with 62 additions and 0 deletions
  1. 62 0
      ch3/ex3rpc.go

+ 62 - 0
ch3/ex3rpc.go

@@ -0,0 +1,62 @@
+package main
+
+/*
+Sample request content:
+	Method: POST
+	Content-type: application/json -> without it JSON-RPC returns a 415.
+	Accept header is not needed.
+
+{
+  "method": "StringService.Length",
+  "params" : [
+    {
+      "Message": "Hello, world"
+    }
+  ],
+  "id": 1
+}
+
+Sample Curl usage:
+
+curl -X POST -H "Content-type: application/json" -d '{"method": "StringService.Length", "params": [{"Message": "Hello, world"}], "Id": 1}' http://localhost:8080/rpc
+
+ */
+
+import (
+	"net/http"
+
+	"github.com/gorilla/rpc/v2"
+	"github.com/gorilla/rpc/v2/json"
+
+	"fmt"
+	"unicode/utf8"
+	"github.com/davecgh/go-spew/spew"
+)
+
+type RPCApiArguments struct {
+	Message string
+}
+
+type RPCAPIResponse struct {
+	Message string
+}
+
+type StringService struct{}
+
+func (s *StringService) Length(q *http.Request, args *RPCApiArguments, r *RPCAPIResponse) error {
+	r.Message = fmt.Sprintf("Your request [%s] is %d characters long",
+		args.Message,
+		utf8.RuneCountInString(args.Message))
+	spew.Dump(r)
+	return nil
+}
+
+func main() {
+	address := ":8080"
+	fmt.Printf("API started on %s\n", address)
+	s := rpc.NewServer()
+	s.RegisterCodec(json.NewCodec(), "application/json")
+	s.RegisterService(new(StringService), "")
+	http.Handle("/rpc", s)
+	http.ListenAndServe(address, nil)
+}