2021-09-08 14:41:28 +02:00
|
|
|
package httpclient
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"io"
|
|
|
|
"net/http"
|
2021-10-23 11:39:51 +02:00
|
|
|
"time"
|
2021-09-08 14:41:28 +02:00
|
|
|
|
|
|
|
"github.com/photoprism/photoprism/internal/event"
|
|
|
|
)
|
|
|
|
|
|
|
|
var log = event.Log
|
|
|
|
|
|
|
|
func Client(debug bool) *http.Client {
|
|
|
|
if debug {
|
2021-09-08 17:46:30 +02:00
|
|
|
return &http.Client{
|
2021-09-08 14:41:28 +02:00
|
|
|
Transport: LoggingRoundTripper{http.DefaultTransport},
|
2021-10-23 11:39:51 +02:00
|
|
|
Timeout: time.Second * 10,
|
2021-09-08 14:41:28 +02:00
|
|
|
}
|
|
|
|
}
|
2021-10-23 11:39:51 +02:00
|
|
|
cl := http.DefaultClient
|
|
|
|
cl.Timeout = time.Second * 10
|
|
|
|
return cl
|
2021-09-08 14:41:28 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// This type implements the http.RoundTripper interface
|
|
|
|
type LoggingRoundTripper struct {
|
|
|
|
proxy http.RoundTripper
|
|
|
|
}
|
|
|
|
|
|
|
|
func (lrt LoggingRoundTripper) RoundTrip(req *http.Request) (res *http.Response, e error) {
|
|
|
|
// Do "before sending requests" actions here.
|
2021-09-09 11:08:45 +02:00
|
|
|
log.Debugf("Sending request to %v\n", req.URL.String())
|
|
|
|
|
2021-09-08 14:41:28 +02:00
|
|
|
// Send the request, get the response (or the error)
|
|
|
|
res, e = lrt.proxy.RoundTrip(req)
|
|
|
|
|
|
|
|
// Handle the result.
|
|
|
|
if e != nil {
|
|
|
|
log.Errorf("Error: %v", e)
|
|
|
|
} else {
|
|
|
|
log.Debugf("Received %v response\n", res.Status)
|
|
|
|
|
2021-09-08 17:46:30 +02:00
|
|
|
// Copy body into buffer for logging
|
2021-09-08 14:41:28 +02:00
|
|
|
buf := new(bytes.Buffer)
|
|
|
|
_, err := io.Copy(buf, res.Body)
|
|
|
|
if err != nil {
|
|
|
|
log.Errorf("Error: %v", err)
|
|
|
|
}
|
2021-09-20 19:19:59 +02:00
|
|
|
log.Debugf("Header: %s\n", res.Header)
|
2021-09-08 14:41:28 +02:00
|
|
|
log.Debugf("Reponse Body: %s\n", buf.String())
|
|
|
|
res.Body = io.NopCloser(buf)
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|