~evanj/cms

ref: 26671b0ca2b523aebded55a95b2f6601db011825 cms/pkg/e3/e3.go -rw-r--r-- 2.0 KiB
26671b0cEvan J Feat(file.go): Upload files concurrently complete. Fixed bug in E3 path 2 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package e3

import (
	"bytes"
	"context"
	"fmt"
	"io"
	"io/ioutil"
	"mime/multipart"
	"net/http"
	"strings"
)

type E3 struct {
	user, pass, url string
	client          *http.Client
}

const DefaultURL = "https://e3.evanjon.es/api"

func New(user, pass, url string) E3 {
	return E3{
		user,
		pass,
		url,
		http.DefaultClient,
	}
}

func WithClient(user, pass, url string, client *http.Client) E3 {
	return E3{
		user,
		pass,
		url,
		client,
	}
}

func (e3 E3) URL() string {
	return e3.url
}

func (e3 E3) Upload(ctx context.Context, public bool, filename string, file io.Reader) (string, error) {
	var requestBody bytes.Buffer
	mpwriter := multipart.NewWriter(&requestBody)

	filewriter, err := mpwriter.CreateFormFile("data", filename)
	if err != nil {
		return "", err
	}
	if _, err := io.Copy(filewriter, file); err != nil {
		return "", err
	}

	if public {
		fieldwriter, err := mpwriter.CreateFormField("access")
		if err != nil {
			return "", err
		}
		_, err = fieldwriter.Write([]byte("public"))
		if err != nil {
			return "", err
		}
	}

	if err := mpwriter.Close(); err != nil {
		return "", err
	}

	// Request as usual.
	req, err := http.NewRequestWithContext(ctx, "POST", e3.url, &requestBody)
	if err != nil {
		return "", err
	}

	req.SetBasicAuth(e3.user, e3.pass)
	req.Header.Set("Content-Type", mpwriter.FormDataContentType())

	resp, err := e3.client.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	bytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	res := strings.TrimSpace(string(bytes))
	if resp.StatusCode != http.StatusOK {
		return "", fmt.Errorf("%s", res)
	}
	return res, nil
}

func (e3 E3) Proxy(ctx context.Context, objectURL string) ([]byte, error) {
	req, err := http.NewRequestWithContext(ctx, "GET", objectURL, nil)
	if err != nil {
		return []byte{}, err
	}
	req.SetBasicAuth(e3.user, e3.pass)

	resp, err := e3.client.Do(req)
	if err != nil {
		return []byte{}, err
	}
	defer resp.Body.Close()

	bytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return []byte{}, err
	}

	return bytes, nil
}