48 lines
1.4 KiB
Go
48 lines
1.4 KiB
Go
package internal
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
"net/url"
|
|
"time"
|
|
|
|
"gitea.dwysokinski.me/twhelp/dcbot/internal/adapter"
|
|
"gitea.dwysokinski.me/twhelp/dcbot/internal/twhelp"
|
|
"github.com/kelseyhightower/envconfig"
|
|
"golang.org/x/time/rate"
|
|
)
|
|
|
|
type twhelpClientConfig struct {
|
|
URL *url.URL `envconfig:"URL" required:"true"`
|
|
Timeout time.Duration `envconfig:"TIMEOUT" default:"10s"`
|
|
RateLimiterEnabled bool `envconfig:"RATE_LIMITER_ENABLED" default:"false"`
|
|
RateLimiterMaxRequestsPerSecond float64 `envconfig:"RATE_LIMITER_MAX_REQUESTS_PER_SECOND" default:"50"`
|
|
RateLimiterRequestBurst int `envconfig:"RATE_LIMITER_REQUEST_BURST" default:"5"`
|
|
}
|
|
|
|
func NewTWHelpService(version string) (*adapter.TWHelpHTTP, error) {
|
|
var cfg twhelpClientConfig
|
|
if err := envconfig.Process("TWHELP", &cfg); err != nil {
|
|
return nil, fmt.Errorf("envconfig.Process: %w", err)
|
|
}
|
|
|
|
opts := []twhelp.ClientOption{
|
|
twhelp.WithBaseURL(cfg.URL.String()),
|
|
twhelp.WithHTTPClient(&http.Client{
|
|
Timeout: cfg.Timeout,
|
|
}),
|
|
twhelp.WithUserAgent("TWHelpDCBot/" + version),
|
|
}
|
|
|
|
if cfg.RateLimiterEnabled {
|
|
opts = append(opts, twhelp.WithRateLimiter(rate.NewLimiter(rate.Limit(cfg.RateLimiterMaxRequestsPerSecond), cfg.RateLimiterRequestBurst)))
|
|
}
|
|
|
|
client, err := twhelp.NewClientWithResponses("", opts...)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return adapter.NewTWHelpHTTP(client), nil
|
|
}
|