literal.go (1561B)
1 package rpc 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "io/ioutil" 7 "net/http" 8 ) 9 10 type literalBackend struct { 11 svc *LiteralProxyService 12 } 13 14 func NewBackend(svc *LiteralProxyService) *literalBackend { 15 return &literalBackend { 16 svc: svc, 17 } 18 19 } 20 21 func inJson(b []byte) (*jsonRpcMsgFull, error) { 22 msg := &jsonRpcMsgFull{} 23 err := json.Unmarshal(b, msg) 24 return msg, err 25 } 26 27 func (l *literalBackend) ServeHTTP(w http.ResponseWriter, r *http.Request) { 28 var err error 29 30 b, err := ioutil.ReadAll(r.Body) 31 if err != nil { 32 s := fmt.Sprintf("Status: %d Not valid jsonrpc request", http.StatusInternalServerError) 33 w.Write([]byte(s)) 34 return 35 } 36 37 msg, err := inJson(b) 38 if err != nil { 39 s := fmt.Sprintf("Status: %d Not valid jsonrpc request", http.StatusBadRequest) 40 w.Write([]byte(s)) 41 return 42 } 43 44 // TODO: make sure getblockbynumber is hex input 45 switch msg.Method { 46 case "eth_getTransactionByHash": 47 b, err = l.svc.GetTransactionByHash(r.Context(), msg.Id, msg.Params[0].(string)) 48 case "eth_getTransactionReceipt": 49 b, err = l.svc.GetTransactionReceipt(r.Context(), msg.Id, msg.Params[0].(string)) 50 case "eth_getBlockByHash": 51 b, err = l.svc.GetBlockByHash(r.Context(), msg.Id, msg.Params[0].(string)) 52 case "eth_getBlockByNumber": 53 b, err = l.svc.GetBlockByNumber(r.Context(), msg.Id, msg.Params[0].(string)) 54 default: 55 s := fmt.Sprintf("Status: %d Method not supported", http.StatusBadRequest) 56 w.Write([]byte(s)) 57 return 58 } 59 60 if err != nil { 61 w.WriteHeader(http.StatusNotFound) 62 return 63 } 64 65 w.WriteHeader(http.StatusOK) 66 w.Write([]byte(b)) 67 }