Golang http包下FileServer的使用


FileServer文檔:https://godoc.org/net/http#FileServer

今天看到http的 Handle 方法,所以就像試試,就找到FileServer

FileServer:

  

           1.www.xx.com/ 根路徑 直接使用

      http.Handle("/", http.FileServer(http.Dir("/tmp")))

  
     2.www.xx.com/c/ 帶有請求路徑的 需要添加函數
      http.Handle("/c/", http.StripPrefix("/c/", http.FileServer(http.Dir("/tmp"))))

example:
package main

import (
        "io"
        "log"
        "net/http"
)

func helloHandler(rw http.ResponseWriter, req *http.Request) {
        url := req.Method + " " + req.URL.Path
        if req.URL.RawQuery != "" {
                url += "?" + req.URL.RawQuery
        }
        log.Println(url)
        io.WriteString(rw, "hello world")
}

func main() {
        http.Handle("/hello", http.NotFoundHandler())
        http.Handle("/dir",http.StripPrefix("/dir", http.FileServer(http.Dir("/usr/local/"))))
        err := http.ListenAndServe(":8080", nil)
        //err := http.ListenAndServe(":8080",http.FileServer(http.Dir("/usr/local/")))
        if err != nil {
                log.Fatal("...")
        }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM