11package jsonrpc_server
22
33import (
4- "github.com/DizoftTeam/jsonrpc_server/utils"
5-
6- "github.com/mitchellh/mapstructure"
7-
84 "encoding/json"
95 "fmt"
106 "log"
117 "net/http"
8+ "os"
129 "reflect"
1310 "strings"
11+
12+ "github.com/DizoftTeam/jsonrpc_server/utils"
13+ "github.com/mitchellh/mapstructure"
1414)
1515
1616const (
@@ -20,6 +20,8 @@ const (
2020var (
2121 methods = map [string ]Method {} // Array of methods
2222 httpRequest * http.Request // Current request
23+
24+ jlog = log .New (os .Stderr , "[JSONRpc]" , log .LstdFlags )
2325)
2426
2527// RPCRequest RPC struct
@@ -60,7 +62,7 @@ func Register(name string, handler RPCMethod) {
6062func RegisterFunc (name string , method Method ) {
6163 methods [name ] = method
6264
63- log .Printf ("Register method: %v\n " , name )
65+ jlog .Printf ("Register method: %v\n " , name )
6466}
6567
6668// NewSession create new request session
@@ -72,8 +74,34 @@ func NewSession() *Session {
7274
7375// --------------- PUBLIC ---------------
7476
75- // Handler Main point function
76- func Handler (w http.ResponseWriter , r * http.Request ) {
77+ // CustomHandler used for custom incoming messages point (like WS)
78+ func CustomHandler (rawJsonData []byte ) string {
79+ var request interface {}
80+ var response string
81+
82+ if err := json .Unmarshal (rawJsonData , & request ); err != nil {
83+ return `{"jsonrpc": "2.0", "error": {"code": -42700, "message": "Common Error"}}`
84+ }
85+
86+ reqType := reflect .ValueOf (request ).Kind ()
87+
88+ if reqType == reflect .Slice {
89+ var responses []string
90+
91+ for _ , item := range request .([]interface {}) {
92+ responses = append (responses , processRequest (item .(map [string ]interface {})))
93+ }
94+
95+ response = fmt .Sprintf ("[%s]" , strings .Join (responses , "," ))
96+ } else {
97+ response = processRequest (request .(map [string ]interface {}))
98+ }
99+
100+ return response
101+ }
102+
103+ // HttpHandler Main point function of http handler
104+ func HttpHandler (w http.ResponseWriter , r * http.Request ) {
77105 defer r .Body .Close ()
78106
79107 w .Header ().Add ("Content-Type" , "application/json" )
0 commit comments