Skip to content

Commit

Permalink
WithUserAgent() pool option.
Browse files Browse the repository at this point in the history
  • Loading branch information
fiatjaf committed Sep 26, 2024
1 parent 2edc0fb commit 0caf8de
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 5 deletions.
17 changes: 15 additions & 2 deletions pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ type SimplePool struct {
signatureChecker func(Event) bool
penaltyBoxMu sync.Mutex
penaltyBox map[string][2]float64
userAgent string
}

type DirectedFilters struct {
Expand Down Expand Up @@ -120,10 +121,20 @@ func (h WithEventMiddleware) ApplyPoolOption(pool *SimplePool) {
pool.eventMiddleware = append(pool.eventMiddleware, h)
}

// WithUserAgent sets the user-agent header for all relay connections in the pool.
func WithUserAgent(userAgent string) withUserAgentOpt { return withUserAgentOpt(userAgent) }

type withUserAgentOpt string

func (h withUserAgentOpt) ApplyPoolOption(pool *SimplePool) {
pool.userAgent = string(h)
}

var (
_ PoolOption = (WithAuthHandler)(nil)
_ PoolOption = (WithEventMiddleware)(nil)
_ PoolOption = WithPenaltyBox()
_ PoolOption = WithUserAgent("")
)

func (pool *SimplePool) EnsureRelay(url string) (*Relay, error) {
Expand All @@ -146,7 +157,6 @@ func (pool *SimplePool) EnsureRelay(url string) (*Relay, error) {
}

// try to connect
var err error
// we use this ctx here so when the pool dies everything dies
ctx, cancel := context.WithTimeout(pool.Context, time.Second*15)
defer cancel()
Expand All @@ -156,7 +166,10 @@ func (pool *SimplePool) EnsureRelay(url string) (*Relay, error) {
opts = append(opts, WithSignatureChecker(pool.signatureChecker))
}

if relay, err = RelayConnect(ctx, nm, opts...); err != nil {
relay = NewRelay(context.Background(), url, opts...)
relay.RequestHeader.Set("User-Agent", pool.userAgent)

if err := relay.Connect(ctx); err != nil {
if pool.penaltyBox != nil {
// putting relay in penalty box
pool.penaltyBoxMu.Lock()
Expand Down
4 changes: 1 addition & 3 deletions relay.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ func NewRelay(ctx context.Context, url string, opts ...RelayOption) *Relay {
ok, _ := e.CheckSignature()
return ok
},
RequestHeader: make(http.Header, 1),
}

for _, opt := range opts {
Expand Down Expand Up @@ -160,9 +161,6 @@ func (r *Relay) ConnectWithTLS(ctx context.Context, tlsConfig *tls.Config) error
defer cancel()
}

if r.RequestHeader == nil {
r.RequestHeader = make(http.Header, 1)
}
if r.RequestHeader.Get("User-Agent") == "" {
r.RequestHeader.Set("User-Agent", "github.com/nbd-wtf/go-nostr")
}
Expand Down

0 comments on commit 0caf8de

Please sign in to comment.