Skip to content

Commit

Permalink
add static file for router
Browse files Browse the repository at this point in the history
  • Loading branch information
coldstar committed Dec 1, 2016
1 parent b3ea948 commit 73d616d
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
9 changes: 9 additions & 0 deletions baa.go
Expand Up @@ -223,6 +223,15 @@ func (b *Baa) Static(prefix string, dir string, index bool, h HandlerFunc) {
b.Get(prefix+"*", staticHandler)
}

// StaticFile shortcut for serve file
func (b *Baa) StaticFile(pattern string, path string, h HandlerFunc) RouteNode {
return b.Get(pattern, func(c *Context) {
if err := serveFile(path, c); err != nil {
c.Error(err)
}
}, h)
}

// SetAutoHead sets the value who determines whether add HEAD method automatically
// when GET method is added. Combo router will not be affected by this value.
func (b *Baa) SetAutoHead(v bool) {
Expand Down
9 changes: 6 additions & 3 deletions static.go
Expand Up @@ -57,7 +57,7 @@ func newStatic(prefix, dir string, index bool, h HandlerFunc) HandlerFunc {
listDir(file, s, c)
} else {
// check index
if err := serveIndex(file+indexPage, c); err != nil {
if err := serveFile(file+indexPage, c); err != nil {
c.Resp.WriteHeader(http.StatusForbidden)
}
}
Expand All @@ -66,7 +66,7 @@ func newStatic(prefix, dir string, index bool, h HandlerFunc) HandlerFunc {
}

if len(file) >= len(indexPage) && file[len(file)-len(indexPage):] == indexPage {
if err := serveIndex(file, c); err != nil {
if err := serveFile(file, c); err != nil {
c.Error(err)
}
} else {
Expand Down Expand Up @@ -109,7 +109,7 @@ func listDir(dir string, s *static, c *Context) {
fmt.Fprintf(c.Resp, "</pre>\n")
}

func serveIndex(file string, c *Context) error {
func serveFile(file string, c *Context) error {
f, err := os.Open(file)
if err != nil {
return err
Expand All @@ -119,6 +119,9 @@ func serveIndex(file string, c *Context) error {
if err != nil {
return err
}
if fs.IsDir() {
return fmt.Errorf("given path is dir, not file")
}
http.ServeContent(c.Resp, c.Req, f.Name(), fs.ModTime(), f)
return nil
}

0 comments on commit 73d616d

Please sign in to comment.