github.com/gocaveman/caveman@v0.0.0-20191211162744-0ddf99dbdf6e/webutil/staticregistry/staticregistry.go (about) 1 // The staticregistry provides registration for default static assets. 2 // Generally used by templates to provide static assets like images, fonts, etc. 3 package staticregistry 4 5 import ( 6 "log" 7 "net/http" 8 9 "github.com/gocaveman/caveman/filesystem/fsutil" 10 "github.com/gocaveman/caveman/webutil" 11 ) 12 13 // OnlyReadableFromMain determines if `Contents()` can be called from packages other than main. 14 // By default we prevent this in order to enforce that object wiring is done in the main package 15 // and not from other components. The intention is to prevent hidden code dependencies from 16 // being introduced. 17 // (TODO: link to doc which explains why in more detail.) 18 var OnlyReadableFromMain = true 19 20 var reg webutil.NamedSequence 21 22 // MustRegister adds a new FileSystem to the include registry. Duplicates (seq, name or value) are not detected or prevented. 23 func MustRegister(seq float64, name string, staticFS http.FileSystem) { 24 reg = append(reg, webutil.NamedSequenceItem{Sequence: seq, Name: name, Value: staticFS}) 25 } 26 27 // Contents returns the current contents of the registry as a NamedSequence. 28 func Contents() webutil.NamedSequence { 29 if OnlyReadableFromMain { 30 webutil.MainOnly(1) 31 } 32 return reg.SortedCopy() 33 } 34 35 // MakeFS sorts the NamedSequence you provide and returns a FileSystem which is 36 // the combination of the Values in this list. Will panic if any value is 37 // not an http.FileSystem. If overrideFS is not nil, it will be included as the 38 // first FileSystem in the stack and will take priority over the rest. 39 // If debug is true then opened files will output debug info to the log. 40 func MakeFS(overrideFS http.FileSystem, contents webutil.NamedSequence, debug bool) http.FileSystem { 41 l := contents.SortedCopy() 42 43 fslist := make([]http.FileSystem, 0, len(l)+1) 44 if overrideFS != nil { 45 46 fs := overrideFS 47 48 if debug { 49 fs = fsutil.NewHTTPFuncFS(func(name string) (http.File, error) { 50 f, err := overrideFS.Open(name) 51 if f != nil { 52 log.Printf("Include file opened from override: %s", name) 53 } 54 return f, err 55 }) 56 } 57 58 fslist = append(fslist, fs) 59 } 60 61 for i := range l { 62 63 item := l[i] 64 65 itemFS := item.Value.(http.FileSystem) 66 fs := itemFS 67 68 if debug { 69 fs = fsutil.NewHTTPFuncFS(func(name string) (http.File, error) { 70 f, err := itemFS.Open(name) 71 if f != nil { 72 log.Printf("Static file opened (sequence=%v, name=%q): %s", item.Sequence, item.Name, name) 73 } 74 return f, err 75 }) 76 } 77 78 fslist = append(fslist, fs) 79 } 80 81 return fsutil.NewHTTPStackedFileSystem(fslist...) 82 }