2024-04-10 17:13:07 +07:00
|
|
|
package reddit
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
2024-07-09 14:12:04 +07:00
|
|
|
"time"
|
2024-04-27 15:16:14 +07:00
|
|
|
|
|
|
|
"github.com/tigorlazuardi/redmage/config"
|
2024-04-29 12:27:46 +07:00
|
|
|
"github.com/tigorlazuardi/redmage/pkg/log"
|
2024-04-10 17:13:07 +07:00
|
|
|
)
|
|
|
|
|
|
|
|
type Client interface {
|
|
|
|
Do(*http.Request) (*http.Response, error)
|
|
|
|
}
|
2024-04-27 15:16:14 +07:00
|
|
|
|
|
|
|
func NewRedditHTTPClient(cfg *config.Config) Client {
|
|
|
|
return &http.Client{
|
|
|
|
Transport: createRoundTripper(cfg),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
type roundTripperFunc func(*http.Request) (*http.Response, error)
|
|
|
|
|
|
|
|
func (ro roundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error) {
|
|
|
|
return ro(req)
|
|
|
|
}
|
|
|
|
|
|
|
|
func createRoundTripper(cfg *config.Config) roundTripperFunc {
|
|
|
|
return func(r *http.Request) (*http.Response, error) {
|
2024-07-09 14:12:04 +07:00
|
|
|
start := time.Now()
|
2024-04-27 15:16:14 +07:00
|
|
|
r.Header.Set("User-Agent", cfg.String("download.useragent"))
|
2024-04-29 12:27:46 +07:00
|
|
|
resp, err := http.DefaultTransport.RoundTrip(r)
|
2024-07-09 14:12:04 +07:00
|
|
|
end := time.Now()
|
|
|
|
duration := end.Sub(start)
|
|
|
|
durStr := (duration / time.Millisecond).String()
|
2024-04-29 12:27:46 +07:00
|
|
|
if err != nil {
|
|
|
|
log.New(r.Context()).
|
|
|
|
Err(err).
|
2024-07-09 14:12:04 +07:00
|
|
|
Errorf("reddit: %s %s %sms", r.Method, r.URL, durStr)
|
2024-04-29 12:27:46 +07:00
|
|
|
return resp, err
|
|
|
|
}
|
|
|
|
if resp.StatusCode >= 400 {
|
|
|
|
log.New(r.Context()).
|
2024-07-09 14:12:04 +07:00
|
|
|
Errorf("reddit: %s %s %sms", r.Method, r.URL, durStr)
|
2024-04-29 12:27:46 +07:00
|
|
|
return resp, err
|
|
|
|
}
|
|
|
|
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
|
|
|
|
log.New(r.Context()).
|
2024-07-09 14:12:04 +07:00
|
|
|
Infof("reddit: %s %s %d %sms", r.Method, r.URL, resp.StatusCode, durStr)
|
2024-04-29 12:27:46 +07:00
|
|
|
}
|
|
|
|
return resp, err
|
2024-04-27 15:16:14 +07:00
|
|
|
}
|
|
|
|
}
|