瀏覽代碼

static file server supports

tags/v0.9.0
jimzhan 9 年之前
父節點
當前提交
0db2906b72
共有 3 個文件被更改,包括 50 次插入1 次删除
  1. +6
    -0
      rex.go
  2. +15
    -1
      server.go
  3. +29
    -0
      server_test.go

+ 6
- 0
rex.go 查看文件

@@ -56,6 +56,12 @@ func Group(path string) *Server {
return Default.Group(path)
}

// FileServer registers a handler to serve HTTP (GET|HEAD) requests
// with the contents of file system under the given directory.
func FileServer(prefix, dir string) {
Default.FileServer(prefix, dir)
}

// Use appends middleware module into the serving list, modules will be served in FIFO order.
func Use(module func(http.Handler) http.Handler) {
Default.Use(module)

+ 15
- 1
server.go 查看文件

@@ -2,7 +2,9 @@ package rex

import (
"fmt"
"log"
"net/http"
"path/filepath"
"reflect"
"runtime"
"time"
@@ -18,10 +20,11 @@ type Server struct {
}

func New() *Server {
return &Server{
self := &Server{
middleware: new(middleware),
mux: mux.NewRouter().StrictSlash(true),
}
return self
}

// build constructs all server/subservers along with their middleware modules chain.
@@ -123,6 +126,17 @@ func (self *Server) Name(r *http.Request) (name string) {
return name
}

// FileServer registers a handler to serve HTTP (GET|HEAD) requests
// with the contents of file system under the given directory.
func (self *Server) FileServer(prefix, dir string) {
if abs, err := filepath.Abs(dir); err == nil {
fs := http.StripPrefix(prefix, http.FileServer(http.Dir(abs)))
self.mux.PathPrefix(prefix).Handler(fs)
} else {
log.Fatalf("Failed to setup file server: %v", err)
}
}

// Use add the middleware module into the stack chain.
func (self *Server) Use(module func(http.Handler) http.Handler) {
self.middleware.stack = append(self.middleware.stack, module)

+ 29
- 0
server_test.go 查看文件

@@ -4,6 +4,8 @@ import (
"io"
"net/http"
"net/http/httptest"
"os"
"path"
"testing"

. "github.com/smartystreets/goconvey/convey"
@@ -152,6 +154,33 @@ func TestGroup(t *testing.T) {
})
}

func TestFileServer(t *testing.T) {
Convey("rex.FileServer", t, func() {
var (
prefix = "/assets/"
filename = "logo.png"
)
tempdir := os.TempDir()
filepath := path.Join(tempdir, filename)
os.Create(filepath)
defer os.Remove(filepath)

app := New()
app.FileServer(prefix, tempdir)

request, _ := http.NewRequest("GET", path.Join(prefix, filename), nil)
response := httptest.NewRecorder()
app.ServeHTTP(response, request)
So(response.Code, ShouldEqual, http.StatusOK)

filename = "index.html"
request, _ = http.NewRequest("HEAD", prefix, nil)
response = httptest.NewRecorder()
app.ServeHTTP(response, request)
So(response.Code, ShouldEqual, http.StatusOK)
})
}

func TestUse(t *testing.T) {
app := New()
app.Get("/", func(w http.ResponseWriter, r *http.Request) {

Loading…
取消
儲存