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

28
web.go
View File

@ -1,6 +1,34 @@
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/elazarl/go-bindata-assetfs/...
//go:generate rm -f static.go
//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),
)
}