go语言实现http服务器时如果处理静态文件,需要用到http.ServeFile:
func ServeFile(w ResponseWriter, r *Request, name string) { dir, file := filepath.Split(name) serveFile(w, r, Dir(dir), file, false)}
首先根据请求路径r.URL.Path判断是否包含静态文件目录,如果存在则直接返回:
img_dir := "/home/qinpeng" if strings.HasPrefix(r.URL.Path,"/img"){ file := img_dir + r.URL.Path[len("/img"):] f,err := os.Open(file) defer f.Close() if err != nil && os.IsNotExist(err){ file = img_dir + "/default.jpg" } http.ServeFile(w,r,file) return }
来源:CSDN
作者:az44yao
链接:https://blog.csdn.net/az44yao/article/details/103799896