一、首先,我的应用目录结构如下图:
分析一下:应用运行文件所在文件夹在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
FileServer returns a handler that serves HTTP requests with the contents of the file system rooted at root.
To use the operating system's file system implementation, use http.Dir:
http.Handle("/", http.FileServer(http.Dir("/tmp")))
2、http.StripPrefix
func StripPrefix(prefix string, h Handler) Handler
StripPrefix returns a handler that serves HTTP requests by removing the given prefix from the request URL's Path and invoking the handler h.
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)
Handle registers the handler for the given pattern in the DefaultServeMux. The
documentation for ServeMux explains how patterns are matched.
func HandleFunc
func HandleFunc(pattern string, handler func(ResponseWriter,
*Request))
HandleFunc registers the handler function for the given pattern in the
DefaultServeMux. The documentation for ServeMux explains how patterns are
matched.
func ListenAndServe
func ListenAndServe(addr string, handler Handler) error
ListenAndServe listens on the TCP network address addr and then calls Serve with
handler to handle requests on incoming connections. Handler is typically nil, in which
case the DefaultServeMux is used.
三、实例代码
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.StripPrefix("/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对应。