golang 文件服务器

在go语言中可以用一句代码做一个文件服务器。如果有很多文件需要通过网页来供其他人下载,可以使用这个方法。

package main

import (
    "log"
    "net/http"
)

func main() {
// 注意斜杠!
http.Handle("/public/", http.StripPrefix("/public/", http.FileServer(http.Dir("public")))) // 正确 //http.Handle("/", http.FileServer(http.Dir("public"))) // 正确(访问根目录时转到public目录) //http.Handle("/public", http.StripPrefix("/public", http.FileServer(http.Dir("public")))) // 错误 //http.Handle("/public", http.FileServer(http.Dir("/public"))) // 错误 //http.Handle("/public", http.FileServer(http.Dir("/public/"))) // 错误 //http.Handle("/public", http.FileServer(http.Dir("./public"))) // 错误! log.Fatal(http.ListenAndServe(":8080", nil)) }

这样在浏览器地址栏里访问 http://localhost:8080/public 时就会显示目录中的文件和子目录了。

 

--End--

posted @ 2016-11-03 17:26  ibg  阅读(1058)  评论(0编辑  收藏  举报