教程集 www.jiaochengji.com
教程集 >  Golang编程  >  正文 go语言http服务处理image/css/js等静态文件

go语言http服务处理image/css/js等静态文件

发布时间:2021-12-10   编辑:jiaochengji.com
教程集为您提供go语言http服务处理image/css/js等静态文件等资源,欢迎您收藏本站,我们将为您提供最新的go语言http服务处理image/css/js等静态文件资源

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判断是否包含静态文件目录,如果存在则直接返回:

<pre><code class="language-plain">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 }</code></pre>

到此这篇关于“go语言http服务处理image/css/js等静态文件”的文章就介绍到这了,更多文章或继续浏览下面的相关文章,希望大家以后多多支持JQ教程网!

您可能感兴趣的文章:
go语言http服务处理image/css/js等静态文件
go语言和php的区别是什么?
flask如何使用javascript
PHP生成静态页面
php与其他语言区别
php和go哪个适合新人
Go语言发展历史、核心、特性及学习路线
Go语言的主要特性和发展影响
【Golang】01 Go 语言初识
Go Web 编程之 静态文件

[关闭]
~ ~