Golang1.8標準庫http.Fileserver跟http.ServerFile小例子

package main

import (
    "fmt"
    "net/http"
    "os"
    "path"
    "strings"
)

var staticfs = http.FileServer(http.Dir("D:\\code\\20160902\\src\\"))

func main() {
    //瀏覽器打開的時候顯示的就是D:\\code\\20160902\\src\\client目錄下的內容"
    http.Handle("/client/", http.FileServer(http.Dir("D:\\code\\20160902\\src\\")))
    http.HandleFunc("/static/", static)
    http.HandleFunc("/js/", js)
    http.HandleFunc("/", route)
    http.ListenAndServe(":1789", nil)
}

func route(w http.ResponseWriter, r *http.Request) {
    fmt.Println(r.URL)
    fmt.Fprintln(w, "welcome")
    r.Body.Close()
}

//這裏可以自行定義安全策略
func static(w http.ResponseWriter, r *http.Request) {
    fmt.Printf("訪問靜態文件:%s\n", r.URL.Path)
    old := r.URL.Path
    r.URL.Path = strings.Replace(old, "/static", "/client", 1)
    staticfs.ServeHTTP(w, r)
}

//設置單文件訪問,不能訪問目錄
func js(w http.ResponseWriter, r *http.Request) {
    fmt.Printf("不能訪問目錄:%s\n", r.URL.Path)
    old := r.URL.Path
    name := path.Clean("D:/code/20160902/src" + strings.Replace(old, "/js", "/client", 1))
    info, err := os.Lstat(name)
    if err == nil {
        if !info.IsDir() {
            http.ServeFile(w, r, name)
        } else {
            http.NotFound(w, r)
        }
    } else {
        http.NotFound(w, r)
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章