Skip to content

Commit

Permalink
rpcserver: GET / support
Browse files Browse the repository at this point in the history
  • Loading branch information
metachris committed Nov 21, 2024
1 parent a33cb04 commit f80623c
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
40 changes: 40 additions & 0 deletions examples/rpcserver/main.go
Original file line number Diff line number Diff line change
@@ -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
}
15 changes: 15 additions & 0 deletions rpcserver/jsonrpc_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit f80623c

Please sign in to comment.