this is the function that should be called in order to answer an rpc call should be registered like "http.HandleFunc("/", httpjsonrpc.Handle)"
(w http.ResponseWriter, r *http.Request)
| 65 | // this is the function that should be called in order to answer an rpc call |
| 66 | // should be registered like "http.HandleFunc("/", httpjsonrpc.Handle)" |
| 67 | func Handle(w http.ResponseWriter, r *http.Request) { |
| 68 | mainMux.RLock() |
| 69 | defer mainMux.RUnlock() |
| 70 | if r.Method == "OPTIONS" { |
| 71 | w.Header().Add("Access-Control-Allow-Headers", "Content-Type") |
| 72 | w.Header().Set("content-type", "application/json;charset=utf-8") |
| 73 | w.Header().Set("Access-Control-Allow-Origin", "*") |
| 74 | return |
| 75 | } |
| 76 | //JSON RPC commands should be POSTs |
| 77 | if r.Method != "POST" { |
| 78 | if mainMux.defaultFunction != nil { |
| 79 | log.Info("HTTP JSON RPC Handle - Method!=\"POST\"") |
| 80 | mainMux.defaultFunction(w, r) |
| 81 | return |
| 82 | } else { |
| 83 | log.Warn("HTTP JSON RPC Handle - Method!=\"POST\"") |
| 84 | return |
| 85 | } |
| 86 | } |
| 87 | //check if there is Request Body to read |
| 88 | if r.Body == nil { |
| 89 | if mainMux.defaultFunction != nil { |
| 90 | log.Info("HTTP JSON RPC Handle - Request body is nil") |
| 91 | mainMux.defaultFunction(w, r) |
| 92 | return |
| 93 | } else { |
| 94 | log.Warn("HTTP JSON RPC Handle - Request body is nil") |
| 95 | return |
| 96 | } |
| 97 | } |
| 98 | request := make(map[string]interface{}) |
| 99 | defer r.Body.Close() |
| 100 | decoder := json.NewDecoder(io.LimitReader(r.Body, common.MAX_REQUEST_BODY_SIZE)) |
| 101 | err := decoder.Decode(&request) |
| 102 | if err != nil { |
| 103 | log.Error("HTTP JSON RPC Handle - json.Unmarshal: ", err) |
| 104 | return |
| 105 | } |
| 106 | if request["method"] == nil { |
| 107 | log.Error("HTTP JSON RPC Handle - method not found: ") |
| 108 | return |
| 109 | } |
| 110 | method, ok := request["method"].(string) |
| 111 | if !ok { |
| 112 | log.Error("HTTP JSON RPC Handle - method is not string: ") |
| 113 | return |
| 114 | } |
| 115 | //get the corresponding function |
| 116 | function, ok := mainMux.m[method] |
| 117 | if ok { |
| 118 | response := function(request["params"].([]interface{})) |
| 119 | data, err := json.Marshal(map[string]interface{}{ |
| 120 | "jsonrpc": "2.0", |
| 121 | "error": response["error"], |
| 122 | "desc": response["desc"], |
| 123 | "result": response["result"], |
| 124 | "id": request["id"], |