123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116 |
- package oss
- import (
- "bytes"
- "io"
- "io/ioutil"
- "strings"
- "github.com/qor/oss"
- "github.com/qor/oss/filesystem"
- "github.com/qor5/admin/media"
- )
- var (
-
- URLTemplate = "/system/{{class}}/{{primary_key}}/{{column}}/{{filename_with_hash}}"
-
- Storage oss.StorageInterface = filesystem.New("public")
- _ media.Media = &OSS{}
- )
- type OSS struct {
- media.Base
- }
- var DefaultURLTemplateHandler = func(oss OSS, option *media.Option) (url string) {
- if url = option.Get("URL"); url == "" {
- url = URLTemplate
- }
- url = strings.Join([]string{strings.TrimSuffix(Storage.GetEndpoint(), "/"), strings.TrimPrefix(url, "/")}, "/")
- if strings.HasPrefix(url, "/") {
- return url
- }
- for _, prefix := range []string{"https://", "http://"} {
- url = strings.TrimPrefix(url, prefix)
- }
-
- return "//" + url
- }
- func (o OSS) GetURLTemplate(option *media.Option) (url string) {
- return DefaultURLTemplateHandler(o, option)
- }
- var DefaultStoreHandler = func(oss OSS, path string, option *media.Option, reader io.Reader) error {
- _, err := Storage.Put(path, reader)
- return err
- }
- func (o OSS) Store(path string, option *media.Option, reader io.Reader) error {
- return DefaultStoreHandler(o, path, option, reader)
- }
- var DefaultRetrieveHandler = func(oss OSS, path string) (media.FileInterface, error) {
- result, err := Storage.GetStream(path)
- if f, ok := result.(media.FileInterface); ok {
- return f, err
- }
- if err == nil {
- buf := []byte{}
- if buf, err = ioutil.ReadAll(result); err == nil {
- result := ClosingReadSeeker{bytes.NewReader(buf)}
- result.Seek(0, 0)
- return result, err
- }
- }
- return nil, err
- }
- func (o OSS) Retrieve(path string) (media.FileInterface, error) {
- return DefaultRetrieveHandler(o, path)
- }
- func (o OSS) URL(styles ...string) string {
- url := o.Base.URL(styles...)
- newurl, err := Storage.GetURL(url)
- if err != nil || len(newurl) == 0 {
- return url
- }
- return newurl
- }
- func (o OSS) String() string {
- url := o.Base.URL()
- newurl, err := Storage.GetURL(url)
- if err != nil || len(newurl) == 0 {
- return url
- }
- return newurl
- }
- type ClosingReadSeeker struct {
- io.ReadSeeker
- }
- func (ClosingReadSeeker) Close() error {
- return nil
- }
|