【翻译】Go Web服务器如何访问目录文件

原创文章,转载请注明: 转载自勤奋的小青蛙
本文链接地址: 【翻译】Go Web服务器如何访问目录文件
Star trails and a bristlecone pine at Bryce Canyon National Park, Utah

Star trails and a bristlecone pine at Bryce Canyon National Park, Utah

原文:http://stackoverflow.com/questions/26559557/how-do-you-serve-a-static-html-file-using-a-go-web-server

所有你需要做的是:

package main

import (
        "net/http"
)

func main() {
        http.Handle("/", http.FileServer(http.Dir("./static")))
        http.ListenAndServe(":3000", nil)
}

假设静态文件位于项目根目录下的名为static的文件夹中。

假如在static目录里有index.html,那么访问:http://localhost:3000 将会返回index.html文件。但是假如index.html中还引入有其他目录下的文件,那么还需要再增加访问路径,不然无法渲染,比如css文件,js文件等。但是在static目录里的文件都是可以通过/路径进行访问。比如还有个clients.html也在static目录里,那么访问http://localhost:3000/clients.html即可。

假如我们想通过访问/static路径来访问服务器端根目录下/public目录里的内容,那么需要额外的增加一个函数:

func StripPrefix(prefix string, h Handler) Handler

增加后的示例代码如下:

package main

import (
        "net/http"
)

func main() {
        http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./public"))))
        http.ListenAndServe(":3000", nil)
}

按照上述代码完成之后,访问服务器目录./public文件夹里的内容,可以通过 http://localhost:3000/static来进行访问。

原创文章,转载请注明: 转载自勤奋的小青蛙
本文链接地址: 【翻译】Go Web服务器如何访问目录文件

文章的脚注信息由WordPress的wp-posturl插件自动生成



|2|left
打赏

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: