http 静态文件

什么是静态文件?如何处理静态文件?静态文件的作用

类型于单独的css  js  图片这些被html文件所需要,而又不会有太大隐私的文件。静态文件用来修饰html等模板。如何只暴露所需要的静态文件?请看下面详解:

先看一下例子:

package main

import (
	"net/http"
)
func main(){
	http.Handle("/",http.FileServer(http.Dir("/")))
	http.ListenAndServe(":80",nil)
}

  访问结果:

访问了整个磁盘上的文件,

修改一下,接着看:

package main

import (
	"net/http"
)
func main(){
	http.Handle("/",http.FileServer(http.Dir("./")))  //当前根目录
	http.ListenAndServe(":80",nil)
}

  访问结果:

当前目录下的所有文件。

上面的情况,放开的权限特别大,这肯定是不行的,主要是不安全的。

看下面的完整的例子:

package main

import (
	"net/http"
	"text/template"
	"fmt"
)
var t1 *template.Template
func init(){
	t,err := template.ParseFiles("./views/index.html")
	if err != nil {
		fmt.Println("paser file err",err)
		return
	}
	t1 = t
}
func index(w http.ResponseWriter, r *http.Request){
	t1.Execute(w,nil)
}
func main(){
	http.HandleFunc("/index",index)
	http.Handle("/media/",http.StripPrefix("/media/",http.FileServer(http.Dir("./media"))))
	// http.Handle("/media/",http.FileServer(http.Dir("./media")))
	http.ListenAndServe(":80",nil)
}

  

当前目录 static, views下是所有的html模板,media下是所有css,js,图片。

访问url:

查看页面所需要css的url:

静态文件其实指的是像css,js,img等一些被模板需要的文件,当它们访问的url不能获取时,那么模板就不能达到预想的效果。所以我们只暴露了所需要的静态文件的目录

查看:

原文地址:https://www.cnblogs.com/wanghaijun999/p/8483987.html