当前位置: 移动技术网 > IT编程>脚本编程>Go语言 > golang搭建静态web服务器的实现方法

golang搭建静态web服务器的实现方法

2018年09月23日  | 移动技术网IT编程  | 我要评论

我胡汉三又回来啦。好久没发文了,为保持平台上的活跃度,我今天就分享下个刚学到的知识,使用golang搭建静态web服务器,亲测可用,附代码!

使用过golang语言的程序猿都应该知道,在使用golang开发的时候,我们是不需要诸如iis,apache,nginx,kangle等服务器支持的。

为什么呢?

原因是,golang的net/http包中已经提供了http的客户端与服务端实现方案。

网上言论都说golang不适合做web开发,相对php、java、.net、nodejs等各类后端语言来说,使用golang来做web开发,确实是一个大工程。

昨晚恰好看到一篇关于使用golang搭建web服务器的文章,心痒难耐,于是自己也折腾了一下,用来练练手。

我是新手上路,照搬文章里的内容,总是磕磕碰碰,每次运行都是找不到路径。代码是这样的:

func main() {
 http.handle("/css/", http.fileserver(http.dir("template")))
 http.handle("/js/", http.fileserver(http.dir("template")))

 http.listenandserve(":8080", nil)
}

目录结构:

src
|--main
| |-main.go
|--template
| |-css
|  |--admin.css
| |-js
|  |--admin.js
| |-html
|  |--404.html

以上运行结果是:找不到template这个路径。

其实我很纳闷,文章作者都可以成功运行起来这个demo,怎么到我这里,就启动不来了呢?

那么问题来了:

1.是什么原因导致程序起不来呢?
2.http.dir()指向的是什么路径?

于是我追踪日志,如下

2018/01/07 11:09:28 open template/html/404.html: the system cannot find the path specified.

发现问题是出在找不到路径上。解决了第一个问题后,那么接下来就需要搞明白http.dir()到底指向的是哪个路径。

我查看了官方例子:

log.fatal(http.listenandserve(":8080", http.fileserver(http.dir("/usr/share/doc"))))

从上面例子http.dir("/usr/share/doc")可看出,该路径指向的是linux系统里的绝对路径。那么问题就解决了:我只需要将http.dir()的路径改为运行时的相对路径,或者使用绝对路径就可以了。

另一个例子,使用http.stripprefix()方法:

// to serve a directory on disk (/tmp) under an alternate url
// path (/tmpfiles/), use stripprefix to modify the request
// url's path before the fileserver sees it:
http.handle("/tmpfiles/", http.stripprefix("/tmpfiles/", http.fileserver(http.dir("/tmp"))))

可看出,tmpfiles是tmp目录下的一个子目录。

既然问题都解决了,那么就修改一下代码,重新运行

func template_dir() string {
 template_dir := "e:\\project\\gotest\\src\\template"
 return template_dir
}

func main() {
 http.handle("/css/", http.fileserver(http.dir(template_dir())))
 http.handle("/js/", http.fileserver(http.dir(template_dir())))

 http.listenandserve(":8080", nil)
}

编译运行后,在浏览器中输入localhost:8080/css/,可成功看到template/css/目录下的admin.css文件。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网