Skip to content

Latest commit

 

History

History
42 lines (30 loc) · 1.08 KB

golang_file_server.md

File metadata and controls

42 lines (30 loc) · 1.08 KB

根目录URL处理

package main

import (
	"net/http"
)

func main() {
	http.Handle("/", http.FileServer(http.Dir("/tmp"))
	log.Fatal(http.ListenAndServe(":8080", nil))
	
	// or
	// log.Fatal(http.ListenAndServe(":8080", 
	//			http.FileServer(http.Dir("/usr/share/doc"))))
}

备注:如果使用暴露dir的方式存在安全隐患的,也可以采用serveFile的方式进行

http.HandleFunc("/static2/", func(w http.ResponseWriter, r *http.Request) {
	// !TODO Add check file access or other thing
	http.ServeFile(w, r, r.URL.Path[1:])
})

前缀目录url处理

package main

import (
	"net/http"
)

func main() {
	http.Handle("/tmp/", http.StripPrefix("/tmp/", http.FileServer(http.Dir("/tmp/static"))))
	http.ListenAndServe(":8080", nil)
}

参考:

  1. Golang. What to use? http.ServeFile(..) or http.FileServer(..)?
  2. golang Http ServerFile
  3. golang Http FileServer