Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@mediocregopher
Last active September 10, 2015 19:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mediocregopher/f35d61ffdec752a90ef4 to your computer and use it in GitHub Desktop.
Save mediocregopher/f35d61ffdec752a90ef4 to your computer and use it in GitHub Desktop.
Demonstrating a simple wrapper around gorilla's json2 rpc abstraction
package main
import (
"bytes"
"log"
"math/rand"
"net/http"
"time"
"github.com/gorilla/rpc/v2"
"github.com/gorilla/rpc/v2/json2"
)
func main() {
rand.Seed(time.Now().UTC().UnixNano())
s := rpc.NewServer()
s.RegisterCodec(LoggerCodec{json2.NewCodec()}, "application/json")
s.RegisterService(RandRPC{}, "")
go func() {
log.Print("listening")
http.ListenAndServe(":8888", s)
}()
time.Sleep(1 * time.Second)
body, err := json2.EncodeClientRequest("RandRPC.Foo", &struct{}{})
if err != nil {
log.Fatal(err)
}
r, err := http.NewRequest("POST", "http://localhost:8888/", bytes.NewBuffer(body))
if err != nil {
log.Fatal(err)
}
r.Header.Set("Content-Type", "application/json")
http.DefaultClient.Do(r)
time.Sleep(500 * time.Millisecond)
}
package main
import (
"errors"
"math/rand"
"net/http"
)
type RandRPC struct{}
func (rr RandRPC) Foo(r *http.Request, args *struct{}, res *struct{}) error {
if rand.Intn(2) == 0 {
return errors.New("there was an ERROR NOOOOOO")
}
return nil
}
package main
import (
"log"
"net/http"
"github.com/gorilla/rpc/v2"
"github.com/gorilla/rpc/v2/json2"
)
type LoggerCodec struct {
c *json2.Codec
}
func (l LoggerCodec) NewRequest(r *http.Request) rpc.CodecRequest {
return LoggerCodecRequest{
CodecRequest: l.c.NewRequest(r).(*json2.CodecRequest),
r: r,
}
}
type LoggerCodecRequest struct {
*json2.CodecRequest
r *http.Request
}
func (lc LoggerCodecRequest) ReadRequest(args interface{}) error {
err := lc.CodecRequest.ReadRequest(args)
if err != nil {
return err
}
method, _ := lc.CodecRequest.Method()
log.Printf("Request from %s for method %s with args %+v", lc.r.RemoteAddr, method, args)
return nil
}
func (lc LoggerCodecRequest) WriteResponse(w http.ResponseWriter, reply interface{}) {
log.Printf("Request from %s successful", lc.r.RemoteAddr)
lc.CodecRequest.WriteResponse(w, reply)
}
func (lc LoggerCodecRequest) WriteError(w http.ResponseWriter, status int, err error) {
log.Printf("Request from %s not successful: %d - %s", lc.r.RemoteAddr, status, err)
lc.CodecRequest.WriteError(w, status, err)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment