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

这篇文章主要介绍了golang搭建静态web服务器的实现方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

我胡汉三又回来啦。好久没发文了,为保持平台上的活跃度,我今天就分享下个刚学到的知识,使用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文件。

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

以上就是golang搭建静态web服务器的实现方法的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » 其他教程