For static HTML page CSS and js files, etc., need to use the net / http package deal with the following functions
StripPrefix function
func StripPrefix(prefix string, h Handler) Handler
StripPrefix returns a processor, URL.Path field of the processor will request given prefix prefix removal process after referred h. StripPrefix will not respond to request for a given prefix 404 page not found to URL.Path field
FileServer function
func FileServer(root FileSystem) Handler
FileServer returns an interface to use FileSystem root to provide file access services HTTP handler. To use the operating system FileSystem interface, you can use http.Dir:
http.Handle("/", http.FileServer(http.Dir("/tmp")))
- type FileSystem
type FileSystem interface {
Open(name string) (File, error)
}
FileSystem interface access to a list of named files. File path separator is '/', regardless of the host operating system conventions
- type Dir
type Dir string
Dir limited to a specified directory tree using the local file system to achieve http.FileSystem interface. Empty Dir be considered ".", Which represents the current directory
- func (Dir) Open
func (d Dir) Open(name string) (File, error)
Examples
Static files directory structure of the project
css style template index.html file Address introduced
<link type="text/css" rel="stylesheet" href="static/css/style.css" >
Handling of static files
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("views/static/"))))
Description:
/ static / will match to / static path / beginning, when the browser requests style.css file index.html page, static prefix will be replaced with the views / static, then go to the views / static / css directory Find style.css file
package main
import (
"html/template"
"net/http"
)
// IndexHandler 去首页
func IndexHandler(w http.ResponseWriter, r *http.Request) {
//解析模板
t := template.Must(template.ParseFiles("views/index.html"))
//执行
t.Execute(w, "")
}
func main() {
//设置处理静态资源
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("views/static/"))))
http.Handle("/pages/", http.StripPrefix("/pages/", http.FileServer(http.Dir("views/pages/"))))
http.HandleFunc("/", IndexHandler)
http.ListenAndServe(":8080", nil)
}