moved code out of main, made web package

This commit is contained in:
Stephen McQuay 2017-01-26 19:15:47 -08:00
parent 04fa2f73a7
commit 85296b4e1b
No known key found for this signature in database
GPG Key ID: 1ABF428F71BAFC3D
2 changed files with 37 additions and 18 deletions

View File

@ -6,22 +6,15 @@ import (
"os" "os"
"strconv" "strconv"
"github.com/elazarl/go-bindata-assetfs"
"mcquay.me/web" "mcquay.me/web"
) )
func main() { func main() {
var fs http.FileSystem static := ""
if os.Getenv("SM_DEV") == "" { if s := os.Getenv("STATIC"); s != "" {
fs = &assetfs.AssetFS{ static = s
Asset: web.Asset,
AssetDir: web.AssetDir,
AssetInfo: web.AssetInfo,
Prefix: "static",
}
} else {
fs = http.Dir(os.Getenv("SM_STATIC"))
} }
port := 8000 port := 8000
if os.Getenv("PORT") != "" { if os.Getenv("PORT") != "" {
p, err := strconv.Atoi(os.Getenv("PORT")) p, err := strconv.Atoi(os.Getenv("PORT"))
@ -31,13 +24,11 @@ func main() {
} }
port = p port = p
} }
// XXX: beware: I've copy/pasted this twice now and been confused because
// I ought to have been using my own servemux sm := http.NewServeMux()
http.Handle(
"/", web.NewServer(sm, static)
http.FileServer(fs), if err := http.ListenAndServe(fmt.Sprintf(":%d", port), sm); err != nil {
)
if err := http.ListenAndServe(fmt.Sprintf(":%d", port), nil); err != nil {
fmt.Fprintf(os.Stderr, "problem serving: %v\n", err) fmt.Fprintf(os.Stderr, "problem serving: %v\n", err)
os.Exit(1) os.Exit(1)
} }

28
web.go
View File

@ -1,6 +1,34 @@
package web package web
import (
"net/http"
"path/filepath"
assetfs "github.com/elazarl/go-bindata-assetfs"
)
//go:generate go get github.com/jteeuwen/go-bindata/... //go:generate go get github.com/jteeuwen/go-bindata/...
//go:generate go get github.com/elazarl/go-bindata-assetfs/... //go:generate go get github.com/elazarl/go-bindata-assetfs/...
//go:generate rm -f static.go //go:generate rm -f static.go
//go:generate go-bindata -o static.go -pkg=web static/... //go:generate go-bindata -o static.go -pkg=web static/...
func NewServer(sm *http.ServeMux, static string) {
var fs http.FileSystem
if p, d := filepath.Split(static); d == "static" {
static = p
}
fs = http.Dir(static)
if static == "" {
fs = &assetfs.AssetFS{
Asset: Asset,
AssetDir: AssetDir,
AssetInfo: AssetInfo,
Prefix: "static",
}
}
sm.Handle(
"/",
http.FileServer(fs),
)
}