Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

rpcserver: GET / support #36

Merged
merged 1 commit into from
Nov 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading