photoprism/internal/httpclient/httpclient.go

61 lines
1.3 KiB
Go
Raw Normal View History

2021-09-08 14:41:28 +02:00
package httpclient
import (
"bytes"
"io"
"net/http"
"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-09-08 17:46:30 +02:00
return http.DefaultClient
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())
// Copy body into buffer for logging
//bu := new(bytes.Buffer)
//_, err := io.Copy(bu, req.Body)
//if err != nil {
// log.Errorf("Error: %v", err)
//}
//log.Debugf("Request Header: %s\n", req.Header)
//log.Debugf("Request Body: %s\n", bu.String())
//req.Body = io.NopCloser(bu)
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)
}
log.Debugf("Reponse Body: %s\n", buf.String())
res.Body = io.NopCloser(buf)
}
return
}