Refactor and simplify asset serving

This commit is contained in:
Dan Sosedoff 2015-05-02 20:10:14 -05:00
parent dd2200bdb8
commit 0ac9d72deb
2 changed files with 16 additions and 25 deletions

View File

@ -12,20 +12,16 @@ import (
"github.com/sosedoff/pgweb/pkg/client" "github.com/sosedoff/pgweb/pkg/client"
"github.com/sosedoff/pgweb/pkg/command" "github.com/sosedoff/pgweb/pkg/command"
"github.com/sosedoff/pgweb/pkg/connection" "github.com/sosedoff/pgweb/pkg/connection"
"github.com/sosedoff/pgweb/pkg/data"
) )
var DbClient *client.Client var DbClient *client.Client
func GetHome(c *gin.Context) { func GetHome(c *gin.Context) {
data, err := data.Asset("static/index.html") serveStaticAsset("/index.html", c)
}
if err != nil { func GetAsset(c *gin.Context) {
c.String(400, err.Error()) serveStaticAsset(c.Params.ByName("path"), c)
return
}
c.Data(200, "text/html; charset=utf-8", data)
} }
func GetConnect(c *gin.Context) { func GetConnect(c *gin.Context) {
@ -248,20 +244,3 @@ func GetBookmarks(c *gin.Context) {
c.JSON(200, bookmarks) c.JSON(200, bookmarks)
} }
func GetAsset(c *gin.Context) {
path := "static" + c.Params.ByName("path")
data, err := data.Asset(path)
if err != nil {
c.String(400, err.Error())
return
}
if len(data) == 0 {
c.String(404, "Asset is empty")
return
}
c.Data(200, assetContentType(path), data)
}

View File

@ -5,6 +5,7 @@ import (
"path/filepath" "path/filepath"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/sosedoff/pgweb/pkg/data"
) )
var extraMimeTypes = map[string]string{ var extraMimeTypes = map[string]string{
@ -13,6 +14,7 @@ var extraMimeTypes = map[string]string{
".woff": "application/x-font-woff", ".woff": "application/x-font-woff",
".eot": "application/vnd.ms-fontobject", ".eot": "application/vnd.ms-fontobject",
".svg": "image/svg+xml", ".svg": "image/svg+xml",
".html": "text/html; charset-utf-8",
} }
type Error struct { type Error struct {
@ -72,3 +74,13 @@ func dbCheckMiddleware() gin.HandlerFunc {
return return
} }
} }
func serveStaticAsset(path string, c *gin.Context) {
data, err := data.Asset("static" + path)
if err != nil {
c.String(400, err.Error())
c.Abort()
}
c.Data(200, assetContentType(path), data)
}