2020-06-06 07:44:36 +00:00
|
|
|
package httputil
|
|
|
|
|
|
|
|
import (
|
2020-06-13 07:29:32 +00:00
|
|
|
"context"
|
2020-06-06 07:44:36 +00:00
|
|
|
"io"
|
|
|
|
"net/http"
|
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/diamondburned/cchat-gtk/internal/gts"
|
|
|
|
"github.com/gregjones/httpcache"
|
|
|
|
"github.com/gregjones/httpcache/diskcache"
|
|
|
|
"github.com/peterbourgon/diskv"
|
|
|
|
"github.com/pkg/errors"
|
|
|
|
)
|
|
|
|
|
2020-07-10 23:26:07 +00:00
|
|
|
var basePath = filepath.Join(os.TempDir(), "cchat-gtk-sabotaging-the-desktop-experience")
|
2020-06-06 07:44:36 +00:00
|
|
|
|
2020-07-10 23:26:07 +00:00
|
|
|
var dskcached = http.Client{
|
|
|
|
Timeout: 15 * time.Second,
|
|
|
|
Transport: httpcache.NewTransport(
|
2020-06-06 07:44:36 +00:00
|
|
|
diskcache.NewWithDiskv(diskv.New(diskv.Options{
|
|
|
|
BasePath: basePath,
|
|
|
|
TempDir: filepath.Join(basePath, "tmp"),
|
|
|
|
PathPerm: 0750,
|
|
|
|
FilePerm: 0750,
|
|
|
|
Compression: diskv.NewZlibCompressionLevel(2),
|
|
|
|
CacheSizeMax: 25 * 1024 * 1024, // 25 MiB in memory
|
|
|
|
})),
|
2020-07-10 23:26:07 +00:00
|
|
|
),
|
2020-06-06 07:44:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func AsyncStreamUncached(url string, fn func(r io.Reader)) {
|
|
|
|
gts.Async(func() (func(), error) {
|
2020-06-13 07:29:32 +00:00
|
|
|
r, err := get(context.Background(), url, false)
|
2020-06-06 07:44:36 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return func() {
|
|
|
|
fn(r.Body)
|
|
|
|
r.Body.Close()
|
|
|
|
}, nil
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
func AsyncStream(url string, fn func(r io.Reader)) {
|
|
|
|
gts.Async(func() (func(), error) {
|
2020-06-13 07:29:32 +00:00
|
|
|
r, err := get(context.Background(), url, true)
|
2020-06-06 07:44:36 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return func() {
|
|
|
|
fn(r.Body)
|
|
|
|
r.Body.Close()
|
|
|
|
}, nil
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2020-06-13 07:29:32 +00:00
|
|
|
func get(ctx context.Context, url string, cached bool) (r *http.Response, err error) {
|
|
|
|
// if cached {
|
|
|
|
// r, err = dskcached.Get(url)
|
|
|
|
// } else {
|
|
|
|
// r, err = memcached.Get(url)
|
|
|
|
// }
|
|
|
|
|
|
|
|
q, err := http.NewRequestWithContext(ctx, "GET", url, nil)
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.Wrap(err, "Failed to make a request")
|
2020-06-06 07:44:36 +00:00
|
|
|
}
|
|
|
|
|
2020-06-13 07:29:32 +00:00
|
|
|
r, err = dskcached.Do(q)
|
2020-06-06 07:44:36 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if r.StatusCode < 200 || r.StatusCode > 299 {
|
|
|
|
r.Body.Close()
|
|
|
|
return nil, errors.Errorf("Unexpected status %d", r.StatusCode)
|
|
|
|
}
|
|
|
|
|
|
|
|
return r, nil
|
|
|
|
}
|