1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 |
- 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)
- }
|