-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathprocess.go
75 lines (68 loc) · 1.97 KB
/
process.go
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
package svg
import (
"context"
"io"
"net/http"
"path/filepath"
"strings"
"time"
"github.com/pkg/errors"
"projectforge.dev/projectforge/app/lib/filesystem"
"projectforge.dev/projectforge/app/util"
)
const (
svgPath = "client/src/svg"
ghLineAwesome = "https://raw.githubusercontent.com/icons8/line-awesome/master/svg/"
)
func AddToProject(fs filesystem.FileLoader, src string, tgt string) (*SVG, error) {
ret, err := load(src, tgt)
if err != nil {
return nil, err
}
dst := filepath.Join(svgPath, tgt+util.ExtSVG)
err = fs.WriteFile(dst, []byte(ret.Markup), filesystem.DefaultMode, true)
if err != nil {
return nil, errors.Wrap(err, "unable to write SVG to file ["+tgt+".svg]")
}
return ret, nil
}
func load(src string, tgt string) (*SVG, error) {
url := src
if !strings.HasPrefix(src, "http") {
url = ghLineAwesome + src + util.ExtSVG
}
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
r, err := http.NewRequestWithContext(ctx, http.MethodGet, url, http.NoBody)
if err != nil {
return nil, err
}
rsp, err := http.DefaultClient.Do(r)
defer func() { _ = rsp.Body.Close() }()
if err != nil || rsp.StatusCode == 404 {
if !strings.HasPrefix(src, "http") {
origErr := err
origURL := url
url = ghLineAwesome + src + "-solid.svg"
r, reqErr := http.NewRequestWithContext(ctx, http.MethodGet, url, http.NoBody)
if reqErr != nil {
return nil, reqErr
}
rsp, reqErr = http.DefaultClient.Do(r)
defer func() { _ = rsp.Body.Close() }()
if reqErr != nil {
return nil, errors.Wrapf(origErr, "unable to call URL [%s]", origURL)
}
} else {
return nil, errors.Wrapf(err, "unable to call URL [%s]: %d", url, rsp.StatusCode)
}
}
if rsp.StatusCode != http.StatusOK {
return nil, errors.Errorf("received status [%d] while calling URL [%s]", rsp.StatusCode, url)
}
b, err := io.ReadAll(rsp.Body)
if err != nil {
return nil, errors.Wrapf(err, "unable to read response")
}
return Transform(tgt, b, url)
}