登录
首页 >  Golang >  Go问答

整合单页应用程序的 Go 服务教程

来源:stackoverflow

时间:2024-03-06 14:09:28 186浏览 收藏

小伙伴们对Golang编程感兴趣吗?是否正在学习相关知识点?如果是,那么本文《整合单页应用程序的 Go 服务教程》,就很适合你,本篇文章讲解的知识点主要包括。在之后的文章中也会多多分享相关知识点,希望对大家的知识积累有所帮助!

问题内容

我正在尝试通过 go 服务器提供使用 polymer (https://github.com/polymer/polymer-starter-kit) 构建的示例单页应用程序。

我的目录布局是:

.
├─serve.go
├─static
├───images
├───node_modules
├───src
├───test
├───...
├───index.html

静态文件夹的内容是使用聚合物 cli 自动生成的。

我的serve.go:

func main() {
    router := mux.newrouter()
    router.handlefunc("/api/health", func(w http.responsewriter, r *http.request) {
        // an example api handler
        json.newencoder(w).encode(map[string]bool{"ok": true})
    })

    spa := spahandler{staticpath: "static", indexpath: "index.html"}
    router.pathprefix("/").handler(spa)

    srv := &http.server{
        handler: router,
        addr:    "127.0.0.1:8000",
        // good practice: enforce timeouts for servers you create!
        writetimeout: 15 * time.second,
        readtimeout:  15 * time.second,
    }

    log.fatal(srv.listenandserve())
}

其中 spahandler 和其余代码取自 gorillamux 推荐布局:https://github.com/gorilla/mux#serving-single-page-applications。

当我访问 localhost:8000 时,标题和 favicon 是从 index.html 中正确获取的,但 src 下的 javascript 应用程序未加载:


  

该内容尚未加载,仅显示空白页面。

这是聚合物端的错误路由还是 go 服务器上的错误服务?


解决方案


router.PathPrefix("/").Handler(http.StripPrefix("/",http.FileServer(http.Dir("./static/")

用此替换静态文件路径

今天关于《整合单页应用程序的 Go 服务教程》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>