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"))))
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("...")
        }
}

猜你喜欢

转载自blog.csdn.net/Edu_enth/article/details/89519564