一,法一,针对一个项目
访问html页面,可在main函数中输入:
http.Handle("/static/",
http.StripPrefix("/static/",http.FileServer(http.Dir("./static"))))
static是 放html文件的路径,比如说登陆注册的signup.html和signin.html路径为.../.../static/view,
实现效果:注册以后跳转到登陆页面
操作:在signup.html的ajax中,跳转路径为
success: function (data) {
if (data=='SUCCESS') {
// 成功后跳到登录页
document.getElementById("login_hint").style.display = "block";
setTimeout(() => {
window.location.href = '/static/view/signin.html';
}, 2000);
} else {
alert('注册失败');
}
二,法二,通过go-bindate将静态资源打包进可执行文件,可解决文件相对路径问题
#下载库
go get -v github.com/jteeuwen/go-bindata/...
go get -v github.com/moxiaomomo/go-bindata-assetfs/...
#将$GOPATH/bin关联到$PATH中,可修改~/.bashrc文件(go-bindata-assetfs命令安装在$GOPATH/bin下),添加如下代码:
export
PATH=$PATH:$GOPATH/bin
#cd $GOPATH/src/<你的工程目录>
#将静态文件打包到一个文件夹里
mkdir assets -p && go-bindata-assetfs -pkg assets -o ./assets/asset.go static/..
#修改静态文件处理逻辑
http.Handle("/static/",
http.StripPrefix("/static/",http.FileServer(http.Dir("./static"))))
这样的效果,无论是在哪个目录通过go run 启动server,都不会404错误