WFS(Web File Server) 是一个可以通过浏览器浏览本地托管目录的在线文件服务器。
使用自定义的 ResponseBodyWriter 结构在 Write 函数中重写 http.ResponseWriter
响应内容。
运行程序,访问 http://127.0.0.1:8080/
即可访问 exe 根目录内容。
package main
import (
"bytes"
"log"
"net/http"
"os"
"path/filepath"
)
func codeStarts() string {
return `
Title
FileServer - 驭鲸环球
`
}
func codeEnd() string {
return `
`
}
type ResponseBodyWriter struct {
http.ResponseWriter
body *bytes.Buffer
}
func (r ResponseBodyWriter) Write(b []byte) (int, error) {
if bytes.Equal(b, []byte{60, 112, 114, 101, 62, 10} /**/) {
return r.ResponseWriter.Write([]byte(codeStarts()))
} else if bytes.Equal(b, []byte{60, 47, 112, 114, 101, 62, 10} /*
*/) {
return r.ResponseWriter.Write([]byte(codeEnd()))
} else if bytes.HasPrefix(b, []byte("")) {
s := append([]byte(""), b...)
s = append(s, []byte("")...)
//r.body.Write(s)
return r.ResponseWriter.Write(s)
}
return r.ResponseWriter.Write(b)
}
func middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
w := &ResponseBodyWriter{ResponseWriter: writer, body: &bytes.Buffer{}}
writer = w
next.ServeHTTP(writer, request)
})
}
func main() {
path, _ := filepath.Abs(filepath.Dir(os.Args[0]))
//设置wfs根目录
//path = "D:/Games/Naraka"
fileHandler := http.FileServer(http.Dir(path))
http.Handle("/", middleware(fileHandler))
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Println(err)
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)