Skip to content

Commit 22ef5da

Browse files
committed
Add resources.GetRemote
In Hugo 0.89 we added remote support to `resources.Get`. In hindsight that was not a great idea, as a poll from many Hugo users showed. See Issue #9285 for more details. After this commit `resources.Get` only supports local resource lookups. If you want to support both, you need to use a construct similar to: Also improve some option case handling. ``` {{ resource := "" }} {{ if (urls.Parse $url).IsAbs }} {{ $resource = resources.GetRemote $url }} {{ else }} {{ $resource = resources.Get $url }} {{ end }} ``` Fixes #9285 Fixes #9296
1 parent 5758c37 commit 22ef5da

File tree

7 files changed

+375
-253
lines changed

7 files changed

+375
-253
lines changed

hugolib/resource_chain_test.go

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -408,10 +408,10 @@ FIT: {{ $fit.Name }}|{{ $fit.RelPermalink }}|{{ $fit.Width }}
408408
CSS integrity Data first: {{ $cssFingerprinted1.Data.Integrity }} {{ $cssFingerprinted1.RelPermalink }}
409409
CSS integrity Data last: {{ $cssFingerprinted2.RelPermalink }} {{ $cssFingerprinted2.Data.Integrity }}
410410
411-
{{ $rimg := resources.Get "%[1]s/sunset.jpg" }}
412-
{{ $remotenotfound := resources.Get "%[1]s/notfound.jpg" }}
411+
{{ $rimg := resources.GetRemote "%[1]s/sunset.jpg" }}
412+
{{ $remotenotfound := resources.GetRemote "%[1]s/notfound.jpg" }}
413413
{{ $localnotfound := resources.Get "images/notfound.jpg" }}
414-
{{ $gopherprotocol := resources.Get "gopher://example.org" }}
414+
{{ $gopherprotocol := resources.GetRemote "gopher://example.org" }}
415415
{{ $rfit := $rimg.Fit "200x200" }}
416416
{{ $rfit2 := $rfit.Fit "100x200" }}
417417
{{ $rimg = $rimg | fingerprint }}
@@ -453,8 +453,8 @@ SUNSET REMOTE: sunset_%[1]s.jpg|/sunset_%[1]s.a9bf1d944e19c0f382e0d8f51de690f7d0
453453
FIT REMOTE: sunset_%[1]s.jpg|/sunset_%[1]s_hu59e56ffff1bc1d8d122b1403d34e039f_0_200x200_fit_q75_box.jpg|200
454454
REMOTE NOT FOUND: OK
455455
LOCAL NOT FOUND: OK
456-
PRINT PROTOCOL ERROR1: error calling resources.Get: Get "gopher://example.org": unsupported protocol scheme "gopher"
457-
PRINT PROTOCOL ERROR2: error calling resources.Get: Get "gopher://example.org": unsupported protocol scheme "gopher"
456+
PRINT PROTOCOL ERROR1: error calling resources.GetRemote: Get "gopher://example.org": unsupported protocol scheme "gopher"
457+
PRINT PROTOCOL ERROR2: error calling resources.GetRemote: Get "gopher://example.org": unsupported protocol scheme "gopher"
458458
459459
460460
`, helpers.HashString(ts.URL+"/sunset.jpg", map[string]interface{}{})))
@@ -691,18 +691,18 @@ T6: {{ $bundle1.Permalink }}
691691
`)
692692
b.WithTemplates("home.html", fmt.Sprintf(`
693693
Min CSS: {{ ( resources.Get "css/styles1.css" | minify ).Content }}
694-
Min CSS Remote: {{ ( resources.Get "%[1]s/css/styles1.css" | minify ).Content }}
694+
Min CSS Remote: {{ ( resources.GetRemote "%[1]s/css/styles1.css" | minify ).Content }}
695695
Min JS: {{ ( resources.Get "js/script1.js" | resources.Minify ).Content | safeJS }}
696-
Min JS Remote: {{ ( resources.Get "%[1]s/js/script1.js" | minify ).Content }}
696+
Min JS Remote: {{ ( resources.GetRemote "%[1]s/js/script1.js" | minify ).Content }}
697697
Min JSON: {{ ( resources.Get "mydata/json1.json" | resources.Minify ).Content | safeHTML }}
698-
Min JSON Remote: {{ ( resources.Get "%[1]s/mydata/json1.json" | resources.Minify ).Content | safeHTML }}
698+
Min JSON Remote: {{ ( resources.GetRemote "%[1]s/mydata/json1.json" | resources.Minify ).Content | safeHTML }}
699699
Min XML: {{ ( resources.Get "mydata/xml1.xml" | resources.Minify ).Content | safeHTML }}
700-
Min XML Remote: {{ ( resources.Get "%[1]s/mydata/xml1.xml" | resources.Minify ).Content | safeHTML }}
700+
Min XML Remote: {{ ( resources.GetRemote "%[1]s/mydata/xml1.xml" | resources.Minify ).Content | safeHTML }}
701701
Min SVG: {{ ( resources.Get "mydata/svg1.svg" | resources.Minify ).Content | safeHTML }}
702-
Min SVG Remote: {{ ( resources.Get "%[1]s/mydata/svg1.svg" | resources.Minify ).Content | safeHTML }}
702+
Min SVG Remote: {{ ( resources.GetRemote "%[1]s/mydata/svg1.svg" | resources.Minify ).Content | safeHTML }}
703703
Min SVG again: {{ ( resources.Get "mydata/svg1.svg" | resources.Minify ).Content | safeHTML }}
704704
Min HTML: {{ ( resources.Get "mydata/html1.html" | resources.Minify ).Content | safeHTML }}
705-
Min HTML Remote: {{ ( resources.Get "%[1]s/mydata/html1.html" | resources.Minify ).Content | safeHTML }}
705+
Min HTML Remote: {{ ( resources.GetRemote "%[1]s/mydata/html1.html" | resources.Minify ).Content | safeHTML }}
706706
`, ts.URL))
707707
}, func(b *sitesBuilder) {
708708
b.AssertFileContent("public/index.html", `Min CSS: h1{font-style:bold}`)
@@ -722,13 +722,13 @@ Min HTML Remote: {{ ( resources.Get "%[1]s/mydata/html1.html" | resources.Minify
722722

723723
{"remote", func() bool { return true }, func(b *sitesBuilder) {
724724
b.WithTemplates("home.html", fmt.Sprintf(`
725-
{{$js := resources.Get "%[1]s/js/script1.js" }}
725+
{{$js := resources.GetRemote "%[1]s/js/script1.js" }}
726726
Remote Filename: {{ $js.RelPermalink }}
727-
{{$svg := resources.Get "%[1]s/mydata/svg1.svg" }}
727+
{{$svg := resources.GetRemote "%[1]s/mydata/svg1.svg" }}
728728
Remote Content-Disposition: {{ $svg.RelPermalink }}
729-
{{$auth := resources.Get "%[1]s/authenticated/" (dict "headers" (dict "Authorization" "Bearer abcd")) }}
729+
{{$auth := resources.GetRemote "%[1]s/authenticated/" (dict "headers" (dict "Authorization" "Bearer abcd")) }}
730730
Remote Authorization: {{ $auth.Content }}
731-
{{$post := resources.Get "%[1]s/post" (dict "method" "post" "body" "Request body") }}
731+
{{$post := resources.GetRemote "%[1]s/post" (dict "method" "post" "body" "Request body") }}
732732
Remote POST: {{ $post.Content }}
733733
`, ts.URL))
734734
}, func(b *sitesBuilder) {

hugolib/securitypolicies_test.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -148,19 +148,19 @@ func TestSecurityPolicies(t *testing.T) {
148148
testVariant(c, cb, `(?s).*"dart-sass-embedded" is not whitelisted in policy "security\.exec\.allow".*`)
149149
})
150150

151-
c.Run("resources.Get, OK", func(c *qt.C) {
151+
c.Run("resources.GetRemote, OK", func(c *qt.C) {
152152
c.Parallel()
153-
httpTestVariant(c, `{{ $json := resources.Get "%[1]s/fruits.json" }}{{ $json.Content }}`, "", nil)
153+
httpTestVariant(c, `{{ $json := resources.GetRemote "%[1]s/fruits.json" }}{{ $json.Content }}`, "", nil)
154154
})
155155

156-
c.Run("resources.Get, denied method", func(c *qt.C) {
156+
c.Run("resources.GetRemote, denied method", func(c *qt.C) {
157157
c.Parallel()
158-
httpTestVariant(c, `{{ $json := resources.Get "%[1]s/fruits.json" (dict "method" "DELETE" ) }}{{ $json.Content }}`, `(?s).*"DELETE" is not whitelisted in policy "security\.http\.method".*`, nil)
158+
httpTestVariant(c, `{{ $json := resources.GetRemote "%[1]s/fruits.json" (dict "method" "DELETE" ) }}{{ $json.Content }}`, `(?s).*"DELETE" is not whitelisted in policy "security\.http\.method".*`, nil)
159159
})
160160

161-
c.Run("resources.Get, denied URL", func(c *qt.C) {
161+
c.Run("resources.GetRemote, denied URL", func(c *qt.C) {
162162
c.Parallel()
163-
httpTestVariant(c, `{{ $json := resources.Get "%[1]s/fruits.json" }}{{ $json.Content }}`, `(?s).*is not whitelisted in policy "security\.http\.urls".*`,
163+
httpTestVariant(c, `{{ $json := resources.GetRemote "%[1]s/fruits.json" }}{{ $json.Content }}`, `(?s).*is not whitelisted in policy "security\.http\.urls".*`,
164164
func(b *sitesBuilder) {
165165
b.WithConfigFile("toml", `
166166
[security]

resources/resource_factories/create/create.go

Lines changed: 0 additions & 213 deletions
Original file line numberDiff line numberDiff line change
@@ -16,15 +16,7 @@
1616
package create
1717

1818
import (
19-
"bufio"
20-
"bytes"
21-
"fmt"
22-
"io"
23-
"io/ioutil"
24-
"mime"
2519
"net/http"
26-
"net/http/httputil"
27-
"net/url"
2820
"path"
2921
"path/filepath"
3022
"strings"
@@ -36,13 +28,8 @@ import (
3628

3729
"github.com/gohugoio/hugo/cache/filecache"
3830
"github.com/gohugoio/hugo/common/hugio"
39-
"github.com/gohugoio/hugo/common/maps"
40-
"github.com/gohugoio/hugo/common/types"
41-
"github.com/gohugoio/hugo/helpers"
4231
"github.com/gohugoio/hugo/resources"
4332
"github.com/gohugoio/hugo/resources/resource"
44-
45-
"github.com/pkg/errors"
4633
)
4734

4835
// Client contains methods to create Resource objects.
@@ -150,203 +137,3 @@ func (c *Client) FromString(targetPath, content string) (resource.Resource, erro
150137
})
151138
})
152139
}
153-
154-
// FromRemote expects one or n-parts of a URL to a resource
155-
// If you provide multiple parts they will be joined together to the final URL.
156-
func (c *Client) FromRemote(uri string, options map[string]interface{}) (resource.Resource, error) {
157-
if err := c.validateFromRemoteArgs(uri, options); err != nil {
158-
return nil, err
159-
}
160-
rURL, err := url.Parse(uri)
161-
if err != nil {
162-
return nil, errors.Wrapf(err, "failed to parse URL for resource %s", uri)
163-
}
164-
165-
resourceID := helpers.HashString(uri, options)
166-
167-
_, httpResponse, err := c.cacheGetResource.GetOrCreate(resourceID, func() (io.ReadCloser, error) {
168-
method, reqBody, err := getMethodAndBody(options)
169-
if err != nil {
170-
return nil, errors.Wrapf(err, "failed to get method or body for resource %s", uri)
171-
}
172-
173-
req, err := http.NewRequest(method, uri, reqBody)
174-
if err != nil {
175-
return nil, errors.Wrapf(err, "failed to create request for resource %s", uri)
176-
}
177-
addDefaultHeaders(req)
178-
179-
if _, ok := options["headers"]; ok {
180-
headers, err := maps.ToStringMapE(options["headers"])
181-
if err != nil {
182-
return nil, errors.Wrapf(err, "failed to parse request headers for resource %s", uri)
183-
}
184-
addUserProvidedHeaders(headers, req)
185-
}
186-
187-
res, err := c.httpClient.Do(req)
188-
if err != nil {
189-
return nil, err
190-
}
191-
192-
if res.StatusCode != http.StatusNotFound {
193-
if res.StatusCode < 200 || res.StatusCode > 299 {
194-
return nil, errors.Errorf("failed to retrieve remote resource: %s", http.StatusText(res.StatusCode))
195-
}
196-
}
197-
198-
httpResponse, err := httputil.DumpResponse(res, true)
199-
if err != nil {
200-
return nil, err
201-
}
202-
203-
return hugio.ToReadCloser(bytes.NewReader(httpResponse)), nil
204-
})
205-
if err != nil {
206-
return nil, err
207-
}
208-
defer httpResponse.Close()
209-
210-
res, err := http.ReadResponse(bufio.NewReader(httpResponse), nil)
211-
if err != nil {
212-
return nil, err
213-
}
214-
215-
if res.StatusCode == http.StatusNotFound {
216-
// Not found. This matches how looksup for local resources work.
217-
return nil, nil
218-
}
219-
220-
body, err := ioutil.ReadAll(res.Body)
221-
if err != nil {
222-
return nil, errors.Wrapf(err, "failed to read remote resource %s", uri)
223-
}
224-
225-
filename := path.Base(rURL.Path)
226-
if _, params, _ := mime.ParseMediaType(res.Header.Get("Content-Disposition")); params != nil {
227-
if _, ok := params["filename"]; ok {
228-
filename = params["filename"]
229-
}
230-
}
231-
232-
var extension string
233-
if arr, _ := mime.ExtensionsByType(res.Header.Get("Content-Type")); len(arr) == 1 {
234-
extension = arr[0]
235-
}
236-
237-
// If extension was not determined by header, look for a file extention
238-
if extension == "" {
239-
if ext := path.Ext(filename); ext != "" {
240-
extension = ext
241-
}
242-
}
243-
244-
// If extension was not determined by header or file extention, try using content itself
245-
if extension == "" {
246-
if ct := http.DetectContentType(body); ct != "application/octet-stream" {
247-
if ct == "image/jpeg" {
248-
extension = ".jpg"
249-
} else if arr, _ := mime.ExtensionsByType(ct); arr != nil {
250-
extension = arr[0]
251-
}
252-
}
253-
}
254-
255-
resourceID = filename[:len(filename)-len(path.Ext(filename))] + "_" + resourceID + extension
256-
257-
return c.rs.New(
258-
resources.ResourceSourceDescriptor{
259-
LazyPublish: true,
260-
OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) {
261-
return hugio.NewReadSeekerNoOpCloser(bytes.NewReader(body)), nil
262-
},
263-
RelTargetFilename: filepath.Clean(resourceID),
264-
})
265-
266-
}
267-
268-
func (c *Client) validateFromRemoteArgs(uri string, options map[string]interface{}) error {
269-
if err := c.rs.ExecHelper.Sec().CheckAllowedHTTPURL(uri); err != nil {
270-
return err
271-
}
272-
273-
if method, ok := options["method"].(string); ok {
274-
if err := c.rs.ExecHelper.Sec().CheckAllowedHTTPMethod(method); err != nil {
275-
return err
276-
}
277-
}
278-
return nil
279-
}
280-
281-
func addDefaultHeaders(req *http.Request, accepts ...string) {
282-
for _, accept := range accepts {
283-
if !hasHeaderValue(req.Header, "Accept", accept) {
284-
req.Header.Add("Accept", accept)
285-
}
286-
}
287-
if !hasHeaderKey(req.Header, "User-Agent") {
288-
req.Header.Add("User-Agent", "Hugo Static Site Generator")
289-
}
290-
}
291-
292-
func addUserProvidedHeaders(headers map[string]interface{}, req *http.Request) {
293-
if headers == nil {
294-
return
295-
}
296-
for key, val := range headers {
297-
vals := types.ToStringSlicePreserveString(val)
298-
for _, s := range vals {
299-
req.Header.Add(key, s)
300-
}
301-
}
302-
}
303-
304-
func hasHeaderValue(m http.Header, key, value string) bool {
305-
var s []string
306-
var ok bool
307-
308-
if s, ok = m[key]; !ok {
309-
return false
310-
}
311-
312-
for _, v := range s {
313-
if v == value {
314-
return true
315-
}
316-
}
317-
return false
318-
}
319-
320-
func hasHeaderKey(m http.Header, key string) bool {
321-
_, ok := m[key]
322-
return ok
323-
}
324-
325-
func getMethodAndBody(options map[string]interface{}) (string, io.Reader, error) {
326-
if options == nil {
327-
return "GET", nil, nil
328-
}
329-
330-
if method, ok := options["method"].(string); ok {
331-
method = strings.ToUpper(method)
332-
switch method {
333-
case "GET", "DELETE", "HEAD", "OPTIONS":
334-
return method, nil, nil
335-
case "POST", "PUT", "PATCH":
336-
var body []byte
337-
if _, ok := options["body"]; ok {
338-
switch b := options["body"].(type) {
339-
case string:
340-
body = []byte(b)
341-
case []byte:
342-
body = b
343-
}
344-
}
345-
return method, bytes.NewBuffer(body), nil
346-
}
347-
348-
return "", nil, fmt.Errorf("invalid HTTP method %q", method)
349-
}
350-
351-
return "GET", nil, nil
352-
}

0 commit comments

Comments
 (0)