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)
    }
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值