First, my application directory structure is as follows:
Analysis: The application Run Files folder in the HW, this is the application root directory. Templates are located in Hw/template, where CSS files are in the CSS folder, JavaScript files in the JS folder.
The application is executed in the HW folder, and the JavaScript files in the Template/css/main.css file and Template/js are required to be read during the run.
Second, need to use the following package: "Net/http"
Functions related to: 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 Invok ing the handler H.
Stripprefix handles a request for a path this doesn ' t begin with the prefix by replying with the 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 is 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 is
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.
Third, instance code
1, Hw.go
Package main
import (
"io"
"log" "
net/http"
)
func Hello (w http. Responsewriter, R *http. Request) {
HP: = '
2, Main.css
Body
{
background-color:black;
color:red;
}
The key is: http. Handle ("/template/", http. Stripprefix ("/template/", http. Fileserver (http. Dir ("./template"))) This line of code implements the sharing of static files.
The main cases are:
A, website root directory: http:/127.0.0.1:8000/
b, need to read the CSS file is: http://127.0.0.1:8000/template/css/main.css, note the/template and HTTP. Handle ("/template/" ... corresponding to the template in the.
Four, the Operation effect