WithUserAgent() pool option.

This commit is contained in:
fiatjaf 2024-09-26 19:18:34 -03:00
parent 2edc0fb713
commit 0caf8deb56
2 changed files with 16 additions and 5 deletions

17
pool.go
View File

@ -30,6 +30,7 @@ type SimplePool struct {
signatureChecker func(Event) bool
penaltyBoxMu sync.Mutex
penaltyBox map[string][2]float64
userAgent string
}
type DirectedFilters struct {
@ -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) {
@ -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()
@ -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()

View File

@ -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 {
@ -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")
}