- attach.AbsolutePublicURL builds the absolute public URL of a blob key from storage.uploads.public_url, or from app.url and the public path prefix - it reads the config only, not the values OpenBucket recorded, so a job worker that opened no bucket gets the same URL as serve - attach.ErrNoAbsoluteURL when neither base is configured Plan 35-01, task 5.
51 lines
1.8 KiB
Go
51 lines
1.8 KiB
Go
package attach
|
|
|
|
import (
|
|
"errors"
|
|
"net/url"
|
|
"strings"
|
|
|
|
"git.golem15.com/golem15/summercms/modules/compass"
|
|
)
|
|
|
|
// ErrNoAbsoluteURL is returned by AbsolutePublicURL when the configuration
|
|
// gives no absolute base: neither storage.uploads.public_url nor an absolute
|
|
// app.url is set.
|
|
var ErrNoAbsoluteURL = errors.New("attach: no absolute public URL: set storage.uploads.public_url or app.url")
|
|
|
|
// AbsolutePublicURL returns the absolute public URL of a blob key, for use
|
|
// outside the site, as in mail. With storage.uploads.public_url set it is
|
|
// that base and the key joined by one slash, as PublicURL returns. Otherwise
|
|
// it is app.url, storage.uploads.public_path_prefix (the default prefix when
|
|
// unset) and the key. With neither it returns ErrNoAbsoluteURL; a malformed
|
|
// public_url is its own error.
|
|
//
|
|
// It reads cfg only, never the values OpenBucket recorded, so it returns the
|
|
// same URL in a process that opened no bucket, such as a job worker.
|
|
func AbsolutePublicURL(cfg *compass.Config, key string) (string, error) {
|
|
if cfg == nil {
|
|
return "", ErrNoAbsoluteURL
|
|
}
|
|
key = strings.TrimLeft(key, "/")
|
|
base, err := parsePublicURL(cfg.String("storage.uploads.public_url"))
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if base != nil {
|
|
return strings.TrimRight(base.String(), "/") + "/" + key, nil
|
|
}
|
|
app, err := url.Parse(strings.TrimSpace(cfg.String("app.url")))
|
|
if err != nil || app.Host == "" || (!strings.EqualFold(app.Scheme, "http") && !strings.EqualFold(app.Scheme, "https")) {
|
|
return "", ErrNoAbsoluteURL
|
|
}
|
|
prefix := strings.TrimSpace(cfg.String("storage.uploads.public_path_prefix"))
|
|
if prefix == "" {
|
|
prefix = defaultPublicPathPrefix
|
|
}
|
|
out := app.Scheme + "://" + app.Host + strings.TrimRight(app.Path, "/")
|
|
if prefix = strings.Trim(prefix, "/"); prefix != "" {
|
|
out += "/" + prefix
|
|
}
|
|
return out + "/" + key, nil
|
|
}
|