go语言实现一个简单的文件服务器 http.FileServer - Go语言中文社区

go语言实现一个简单的文件服务器 http.FileServer


package main

import (
    "flag"
    "fmt"
    "github.com/julienschmidt/httprouter"
    "log"
    "net/http"
    "strings"
    "time"
)

func main() {

    root := flag.String("p", "", "file server root directory")
    flag.Parse()

    if len(*root) == 0 {
        log.Fatalln("file server root directory not set")
    }

    if !strings.HasPrefix(*root, "/") {
        log.Fatalln("file server root directory not begin with '/'")
    }

    if !strings.HasSuffix(*root, "/") {
        log.Fatalln("file server root directory not end with '/'")
    }

    p, h := NewFileHandle(*root)
    r := httprouter.New()
    r.GET(p, LogHandle(h))

    log.Fatalln(http.ListenAndServe(":8080", r))
}

func NewFileHandle(path string) (string, httprouter.Handle) {
    return fmt.Sprintf("%s*files", path), func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
        http.StripPrefix(path, http.FileServer(http.Dir(path))).ServeHTTP(w, r)
    }
}

func LogHandle(handle httprouter.Handle) httprouter.Handle {
    return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
        now := time.Now()
        handle(w, r, p)
        log.Printf("%s %s %s done in %v", r.RemoteAddr, r.Method, r.URL.Path, time.Since(now))
    }
}

准备测试文件

1020024-20181127111038776-710033526.png

编译运行

1020024-20181127111058106-1909350684.png

用浏览器访问

1020024-20181127111118908-281947794.png
1020024-20181127111130474-1646543134.png
1020024-20181127111140040-69804360.png
1020024-20181127111152458-1676317363.png
1020024-20181127111203718-1331265530.png
1020024-20181127111214700-1032802747.png

转载于:https://www.cnblogs.com/xiangyang-li/p/10024978.html

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_30826761/article/details/97925967
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-04-18 16:31:02
  • 阅读 ( 1322 )
  • 分类:Go

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢