用golang写gee(day6)

利用http包的http.FileServer,结合动态路由来实现Static方法,随意访问任意路径下的文件。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// create static handler  
func (group *RouterGroup) createStaticHandler(relativePath string, fs http.FileSystem) HandlerFunc {  
	absolutePath := path.Join(group.prefix, relativePath)  
	fileServer := http.StripPrefix(absolutePath, http.FileServer(fs))  
	return func(c *Context) {  
		file := c.Param("filepath")  
		// Check if file exists and/or if we have permission to access it  
		if _, err := fs.Open(file); err != nil {  
			c.Status(http.StatusNotFound)  
			return  
		}  
  
		fileServer.ServeHTTP(c.Writer, c.Req)  
	}  
}  
  
// serve static files  
func (group *RouterGroup) Static(relativePath string, root string) {  
	handler := group.createStaticHandler(relativePath, http.Dir(root))  
	urlPattern := path.Join(relativePath, "/*filepath")  
	// Register GET handlers  
	group.GET(urlPattern, handler)  
}

代码非常浅显易懂。

模板的知识不太了解,暂时不做。

0%