Skip to content
This repository has been archived by the owner on Jun 15, 2023. It is now read-only.

Commit

Permalink
simplify embed/external resource condition
Browse files Browse the repository at this point in the history
  • Loading branch information
boypt committed Jul 21, 2021
1 parent f6aab17 commit 13fe523
Showing 1 changed file with 14 additions and 23 deletions.
37 changes: 14 additions & 23 deletions static/static.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
//go:generate go-bindata -pkg ctstatic -ignore .../.DS_Store -o files.go files/...

package ctstatic

import (
Expand All @@ -9,40 +7,33 @@ import (
"log"
"net/http"
"os"
"path"
)

//go:embed files
var staticFS embed.FS

// FileSystemHandler all static/ files embedded as a Go library
func FileSystemHandler() http.Handler {
if info, err := os.Stat("static/files/"); err == nil && info.IsDir() {
log.Println("Using filesystem static files (dev mode)")
return http.FileServer(http.Dir("static/files/"))
}
if fsys, err := fs.Sub(staticFS, "files"); err == nil {
return http.FileServer(http.FS(fsys))
var curFS fs.FS

const resourcePath = "static/files"

func init() {
if info, err := os.Stat(resourcePath); err == nil && info.IsDir() {
log.Printf("[static] found %s, using external resources.", resourcePath)
curFS = os.DirFS(resourcePath)
} else {
log.Println("FileSystemHandler", err)
curFS, _ = fs.Sub(staticFS, "files")
}
return http.NotFoundHandler()
}

// ReadAll return local file if exists
func FileSystemHandler() http.Handler {
return http.FileServer(http.FS(curFS))
}

func ReadAll(name string) ([]byte, error) {
f, err := Open(name)
f, err := curFS.Open(name)
if err != nil {
return nil, err
}
defer f.Close()
return ioutil.ReadAll(f)
}

func Open(name string) (fs.File, error) {
if info, err := os.Stat("static/files/"); err == nil && info.IsDir() {
diskPath := "static/files/" + name
return os.Open(diskPath)
}
return staticFS.Open(path.Join("files", name))
}

0 comments on commit 13fe523

Please sign in to comment.