diff --git a/examples/rpcserver/main.go b/examples/rpcserver/main.go new file mode 100644 index 0000000..97c9b8a --- /dev/null +++ b/examples/rpcserver/main.go @@ -0,0 +1,40 @@ +package main + +import ( + "context" + "fmt" + "net/http" + + "github.com/flashbots/go-utils/rpcserver" +) + +var listenAddr = ":8080" + +func main() { + handler, err := rpcserver.NewJSONRPCHandler( + rpcserver.Methods{ + "test_foo": HandleTestFoo, + }, + rpcserver.JSONRPCHandlerOpts{ + ServerName: "public_server", + GetResponseContent: []byte("Hello world"), + }, + ) + if err != nil { + panic(err) + } + + // server + server := &http.Server{ + Addr: listenAddr, + Handler: handler, + } + fmt.Println("Starting server.", "listenAddr:", listenAddr) + if err := server.ListenAndServe(); err != nil { + panic(err) + } +} + +func HandleTestFoo(ctx context.Context) (string, error) { + return "foo", nil +} diff --git a/rpcserver/jsonrpc_server.go b/rpcserver/jsonrpc_server.go index 1c379ea..8aa29a1 100644 --- a/rpcserver/jsonrpc_server.go +++ b/rpcserver/jsonrpc_server.go @@ -92,6 +92,8 @@ type JSONRPCHandlerOpts struct { // If true extract value from x-flashbots-origin header // Result can be extracted from the context using GetOrigin ExtractOriginFromHeader bool + // GET response content + GetResponseContent []byte } // NewJSONRPCHandler creates JSONRPC http.Handler from the map that maps method names to method functions @@ -157,6 +159,19 @@ func (h *JSONRPCHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { }() if r.Method != http.MethodPost { + // Respond with GET response content if it's set + if r.Method == http.MethodGet && len(h.GetResponseContent) > 0 { + w.WriteHeader(http.StatusOK) + _, err := w.Write(h.GetResponseContent) + if err != nil { + http.Error(w, errMarshalResponse, http.StatusInternalServerError) + incInternalErrors(h.ServerName) + return + } + return + } + + // Responsd with "only POST method is allowed" http.Error(w, errMethodNotAllowed, http.StatusMethodNotAllowed) incIncorrectRequest(h.ServerName) return