http 静态文件
什么是静态文件?如何处理静态文件?静态文件的作用
类型于单独的css js 图片这些被html文件所需要,而又不会有太大隐私的文件。静态文件用来修饰html等模板。如何只暴露所需要的静态文件?请看下面详解:
先看一下例子:
1 2 3 4 5 6 7 8 9 | package main import ( "net/http" ) func main(){ http.Handle( "/" ,http.FileServer(http.Dir( "/" ))) http.ListenAndServe( ":80" ,nil) } |
访问结果:
访问了整个磁盘上的文件,
修改一下,接着看:
1 2 3 4 5 6 7 8 9 | package main import ( "net/http" ) func main(){ http.Handle( "/" ,http.FileServer(http.Dir( "./" ))) //当前根目录 http.ListenAndServe( ":80" ,nil) } |
访问结果:
当前目录下的所有文件。
上面的情况,放开的权限特别大,这肯定是不行的,主要是不安全的。
看下面的完整的例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | 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不能获取时,那么模板就不能达到预想的效果。所以我们只暴露了所需要的静态文件的目录
查看:
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步