github.com/volts-dev/volts@v0.0.0-20240120094013-5e9c65924106/router/static.go (about) 1 package router 2 3 import ( 4 "net/http" 5 "path/filepath" 6 ) 7 8 func staticHandler(urlPattern string, filePath string) func(c *THttpContext) { 9 fs := http.Dir(filePath) // the filesystem path 10 fileServer := http.StripPrefix(urlPattern, http.FileServer(fs)) // binding a url to file server 11 12 return func(c *THttpContext) { 13 file := filepath.Join(c.pathParams.FieldByName("filepath").AsString()) 14 // Check if file exists and/or if we have permission to access it 15 if _, err := fs.Open(file); err != nil { 16 // 对最后一个控制器返回404 17 if c.handlerIndex == len(c.route.handlers)-1 { 18 c.response.WriteHeader(http.StatusNotFound) 19 } 20 21 log.Warn(err) 22 return 23 } 24 25 fileServer.ServeHTTP(c.response, c.request.Request) 26 c.Apply() //已经服务当前文件并结束 27 } 28 }