Skip to content
Snippets Groups Projects
Commit 7378cc86 authored by Pavel Antonov's avatar Pavel Antonov :asterisk:
Browse files

Merge branch 'feature/PRXS-1714-URLTemplate' into 'master'

Добавлен метод SetURLWithTemplate для структуры File

See merge request perxis/perxis-go!119
parents bb00b270 c8ceb708
No related branches found
No related tags found
No related merge requests found
package files
import (
"bytes"
"fmt"
"io/fs"
"strings"
"text/template"
"git.perx.ru/perxis/perxis-go/pkg/id"
)
......@@ -31,6 +33,20 @@ func (f File) Temporary() bool {
return strings.HasPrefix(f.ID, TemporaryPrefix)
}
func (f *File) SetURLWithTemplate(t *template.Template) error {
if t == nil {
return nil
}
res := new(bytes.Buffer)
if err := t.Execute(res, f); err != nil {
return err
}
f.URL = res.String()
return nil
}
func (f File) Fetch(i interface{}) interface{} {
p, _ := i.(string)
switch p {
......
package files
import (
"testing"
"text/template"
"github.com/stretchr/testify/require"
)
func TestFile_SetURLWithTemplate(t *testing.T) {
tests := []struct {
name string
file *File
template *template.Template
wantErr bool
wantURL string
}{
{
name: "template is nil",
file: &File{
URL: "https://cloud.com/",
},
template: nil,
wantErr: false,
wantURL: "https://cloud.com/",
},
{
name: "template with non-existent field",
file: &File{},
template: template.Must(template.New("url").Parse("{{.NonExistentField}}")),
wantErr: true,
},
{
name: "success",
file: &File{
Size: 1024,
MimeType: "image/png",
Key: "file-key",
},
template: template.Must(template.New("url").Parse("https://cloud-proxy.com/{{.Key}}?size={{.Size}}#{{.MimeType}}")),
wantErr: false,
wantURL: "https://cloud-proxy.com/file-key?size=1024#image/png",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := tt.file.SetURLWithTemplate(tt.template)
if tt.wantErr {
require.Error(t, err)
} else {
require.NoError(t, err)
require.Equal(t, tt.wantURL, tt.file.URL)
}
})
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment