加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Golang1.8标准库http.Fileserver跟http.ServerFile小例子

发布时间:2020-12-16 18:18:16 所属栏目:大数据 来源:网络整理
导读:package mainimport ( "fmt" "net/http" "os" "path" "strings" )var staticfs = http .FileServer( http .Dir( "D:code20160902src" ))func main() { //浏览器打开的时候显示的就是D:code20160902srcclient目录下的内容" http .Handle( "/c
package main

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

var staticfs = http.FileServer(http.Dir("D:code20160902src"))

func main() {
    //浏览器打开的时候显示的就是D:code20160902srcclient目录下的内容"
    http.Handle("/client/",http.FileServer(http.Dir("D:code20160902src")))
    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("访问静态文件:%sn",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("不能访问目录:%sn",r.URL.Path)
    old := r.URL.Path
    name := path.Clean("D:/code/20160902/src" + strings.Replace(old,"/js",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)
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读