Golang 开发web应用时的静态文件处理方法(v0.01)
一、首先,我的应用目录结构如下图: 分析一下:应用运行文件所在文件夹在hw,此即为应用根目录。模板则位于hw/template中,其中css文件在其中的css文件夹,javascript文件在js文件夹。 应用在hw文件夹中被执行,运行过程中需要读取template/css/main.css文件及template/js中的javascript文件。 二、需要用到如下的包:"net/http" 涉及到的函数:http.Fileserver,http.StripPrefix,http.Handle。 1、http.FileServer func FileServer(root FileSystem) Handler
2、http.StripPrefix func StripPrefix(prefix string,h Handler) Handler
StripPrefix handles a request for a path that doesn't begin with prefix by replying with an HTTP 404 not found error. 3、http.Handle func Handle(pattern string,handler Handler) 三、实例代码 1、hw.go package main import ( "io" "log" "net/http" ) func Hello(w http.ResponseWriter,r *http.Request) { hp := `<html> <head> <title>okkkkkk</title> <link rel="stylesheet" href="template/css/main.css" type="text/css" /> </head> <body> <h2>this is a test for golang.</h2> </body> </html>` io.WriteString(w,hp) } func StaticServer(w http.ResponseWriter,r *http.Request) { w.Header().Set("content-type","text/html") staticHandler := http.FileServer(http.Dir("./template/")) staticHandler.ServeHTTP(w,r) return } func main() { http.Handle("/template/",http.StripPrefix("/template/",http.FileServer(http.Dir("./template")))) http.HandleFunc("/",Hello) err := http.ListenAndServe(":8000",nil) if err != nil { log.Fatal("ListenAndServe: ",err.Error()) } } 2、main.css body { background-color: black; color: red; } 关键在:http.Handle("/template/",http.FileServer(http.Dir("./template")))) 这一行代码中实现了静态文件的共享。 主要情况为: a、网站根目录:http:/127.0.0.1:8000/ b、需要读取的css文件为:http://127.0.0.1:8000/template/css/main.css,注意其中的 /template与http.Handle("/template/"...中的template对应。
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |