Allow user to handle/ignore errors in resources.Get

In Hugo 0.90.0 we introduced remote support in `resources.Get`.

But with remote resources comes with a higher chance of failing a build (network issues, remote server down etc.).

Before this commit we always failed the build on any unexpected error.

This commit allows the user to check for any error (and potentially fall back to a default local resource):

```htmlbars
{{ $result := resources.Get "https://gohugo.io/img/hugo-logo.png" }}
{{ with $result }}
        {{ if .Err }}
        {{/* log the error, insert a default image etc. *}}
        {{ else }}
        <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt="">
        {{ end }}
{{ end }}
```

Note that the default behaviour is still to fail the build, but we will delay that error until you start using the `Resource`.

Fixes #9529
This commit is contained in:
Bjørn Erik Pedersen
2021-12-09 16:57:05 +01:00
parent 6260455ba7
commit e4d6ec94b5
10 changed files with 185 additions and 23 deletions

View File

@@ -113,30 +113,40 @@ func (ns *Namespace) getscssClientDartSass() (*dartsass.Client, error) {
// further transformations.
//
// For URLs an additional argument with options can be provided.
func (ns *Namespace) Get(args ...interface{}) (resource.Resource, error) {
if len(args) != 1 && len(args) != 2 {
return nil, errors.New("must provide a filename or URL")
}
filenamestr, err := cast.ToStringE(args[0])
if err != nil {
return nil, err
}
if u, err := url.Parse(filenamestr); err == nil && u.Scheme != "" {
if len(args) == 2 {
options, err := maps.ToStringMapE(args[1])
if err != nil {
return nil, err
}
return ns.createClient.FromRemote(filenamestr, options)
func (ns *Namespace) Get(args ...interface{}) resource.Resource {
get := func(args ...interface{}) (resource.Resource, error) {
if len(args) != 1 && len(args) != 2 {
return nil, errors.New("must provide a filename or URL")
}
return ns.createClient.FromRemote(filenamestr, nil)
filenamestr, err := cast.ToStringE(args[0])
if err != nil {
return nil, err
}
if u, err := url.Parse(filenamestr); err == nil && u.Scheme != "" {
if len(args) == 2 {
options, err := maps.ToStringMapE(args[1])
if err != nil {
return nil, err
}
return ns.createClient.FromRemote(filenamestr, options)
}
return ns.createClient.FromRemote(filenamestr, nil)
}
filenamestr = filepath.Clean(filenamestr)
return ns.createClient.Get(filenamestr)
}
filenamestr = filepath.Clean(filenamestr)
r, err := get(args...)
if err != nil {
// This allows the client to reason about the .Err in the template.
return resources.NewErrorResource(errors.Wrap(err, "error calling resources.Get"))
}
return r
return ns.createClient.Get(filenamestr)
}
// GetMatch finds the first Resource matching the given pattern, or nil if none found.