refactoring: implement review feedback

This commit is contained in:
David Christofas
2020-03-11 14:18:25 +01:00
parent 261429ef72
commit 985c11896f
4 changed files with 27 additions and 41 deletions
+5 -27
View File
@@ -1,33 +1,11 @@
package imgsource
import "image"
import (
"context"
"image"
)
// Source defines the interface for image sources
type Source interface {
Get(path string, ctx SourceContext) (image.Image, error)
}
// NewContext creates a new SourceContext instance
func NewContext() SourceContext {
return SourceContext{
m: make(map[string]interface{}),
}
}
// SourceContext is used to pass source specific parameters
type SourceContext struct {
m map[string]interface{}
}
// GetString tries to cast the value to a string
func (s SourceContext) GetString(key string) string {
if s, ok := s.m[key].(string); ok {
return s
}
return ""
}
// Set sets a value
func (s SourceContext) Set(key string, val interface{}) {
s.m[key] = val
Get(ctx context.Context, path string) (image.Image, error)
}
+11 -2
View File
@@ -1,6 +1,7 @@
package imgsource
import (
"context"
"fmt"
"image"
"net/http"
@@ -28,7 +29,7 @@ const (
)
// Get downloads the file from a webdav service
func (s WebDav) Get(file string, ctx SourceContext) (image.Image, error) {
func (s WebDav) Get(ctx context.Context, file string) (image.Image, error) {
u, _ := url.Parse(s.baseURL)
u.Path = path.Join(u.Path, file)
req, err := http.NewRequest(http.MethodGet, u.String(), nil)
@@ -36,7 +37,10 @@ func (s WebDav) Get(file string, ctx SourceContext) (image.Image, error) {
return nil, fmt.Errorf("could not get the image \"%s\" error: %s", file, err.Error())
}
auth := ctx.GetString(WebDavAuth)
auth, ok := authorization(ctx)
if !ok {
return nil, fmt.Errorf("could not get image \"%s\" error: authorization is missing", file)
}
req.Header.Add("Authorization", auth)
client := &http.Client{}
@@ -55,3 +59,8 @@ func (s WebDav) Get(file string, ctx SourceContext) (image.Image, error) {
}
return img, nil
}
func authorization(ctx context.Context) (string, bool) {
auth, ok := ctx.Value(WebDavAuth).(string)
return auth, ok
}