[关闭]
@Pollux 2017-03-09T13:13:20.000000Z 字数 920 阅读 3114

GoLang 实现一个最简单的http文件服务器

PathToYou


How to use

FileServer.go

  1. package main
  2. import (
  3. "log"
  4. "net/http"
  5. "os"
  6. )
  7. func main() {
  8. os.Mkdir("file", 0777)
  9. http.Handle("/pollux/", http.StripPrefix("/pollux/", http.FileServer(http.Dir("file"))))
  10. err := http.ListenAndServe(":8080", nil)
  11. if err != nil {
  12. log.Fatal("ListenAndServe: ", err)
  13. }
  14. }

func FileServer

TIM截图20170303113018.png

FileServer returns a handler that serves HTTP requests with the contents of the file system rooted at root.To use the operating system's file system implementation, use http.Dir:

func StripPrefix

TIM截图20170303112931.png

StripPrefix returns a handler that serves HTTP requests by removing the given prefix from the request URL's Path and invoking the handler h. StripPrefix handles a request for a path that doesn't begin with prefix by replying with an HTTP 404 not found error.

StripPrefix() 识别 URL 请求中的给定的前缀prefix,如 http://localhost:8080/pollux/ 中的 /pollux/,然后响应函数中的第二个参数 handler h,假如没有识别到给定的前缀,则响应404。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注