亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Golang + 角

Golang + 角

Go
神不在的星期二 2021-12-13 17:11:31
我開始嘗試使用 Go 和 Angular,但我有一個奇怪的問題..我想我只是遺漏了一個小細節,但我無法弄清楚。我正在使用https://github.com/julienschmidt/httprouter作為 Go 的路由器......現在使用 Angular,我應該能夠將 URL 復制并粘貼到瀏覽器中,Angular 應該處理相應的路由,對嗎?我有一個“/登錄”路線。如果通過前端訪問路由....Go 路由基本上只是在做router.NotFound = http.FileServer(http.Dir("./public"))這適用于“/”路線,但不適用于其他任何路線。這似乎是正確的。但是如何正確設置路由,以便 Angular 處理所有路由?
查看完整描述

3 回答

?
江戶川亂折騰

TA貢獻1851條經驗 獲得超5個贊

這就是我在標準 Go 庫中使用的,路由效果很好。


在此處查看Adapt 功能


// Creates a new serve mux

mux := http.NewServeMux()


// Create room for static files serving

mux.Handle("/node_modules/", http.StripPrefix("/node_modules", http.FileServer(http.Dir("./node_modules"))))

mux.Handle("/html/", http.StripPrefix("/html", http.FileServer(http.Dir("./html"))))

mux.Handle("/js/", http.StripPrefix("/js", http.FileServer(http.Dir("./js"))))

mux.Handle("/ts/", http.StripPrefix("/ts", http.FileServer(http.Dir("./ts"))))

mux.Handle("/css/", http.StripPrefix("/css", http.FileServer(http.Dir("./css"))))


// Do your api stuff**

mux.Handle("/api/register", util.Adapt(api.RegisterHandler(mux),

    api.GetMongoConnection(),

    api.CheckEmptyUserForm(),

    api.EncodeUserJson(),

    api.ExpectBody(),

    api.ExpectPOST(),


))

mux.HandleFunc("/api/login", api.Login)

mux.HandleFunc("/api/authenticate", api.Authenticate)


// Any other request, we should render our SPA's only html file,

// Allowing angular to do the routing on anything else other then the api    

// and the files it needs for itself to work.

// Order here is critical. This html should contain the base tag like

// <base href="/"> *href here should match the HandleFunc path below 

mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {

    http.ServeFile(w, r, "html/index.html")

})


查看完整回答
反對 回復 2021-12-13
?
幕布斯6054654

TA貢獻1876條經驗 獲得超7個贊

您可以http直接使用該包。


索引頁

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {

    http.ServeFile(w, r, "./public/index.html")

})

這將為所有與路由不匹配的請求提供 index.html 文件。


文件服務器

http.Handle("/public/", http.StripPrefix("/public/", http.FileServer(http.Dir("./public"))))

這將為公共目錄中的所有文件提供服務。


不要忘記啟動你的服務器


http.ListenAndServe(":8000", nil)


查看完整回答
反對 回復 2021-12-13
?
慕斯王

TA貢獻1864條經驗 獲得超2個贊

使用 goji 微框架


https://github.com/zenazn/goji


很容易使用


func render_html_page(w http.ResponseWriter, url string) {

    t, err := template.ParseFiles(url) 

    if err != nil {

        panic (err)

    }

    t.Execute(w, nil)

}


func index(c web.C, w http.ResponseWriter, r *http.Request) {

    render_html_page(w, "./public/index.html")

}


func main() {

        goji.Get("/", index)

        goji.Serve()

}

此代碼有效,您只需要進行導入


查看完整回答
反對 回復 2021-12-13
  • 3 回答
  • 0 關注
  • 173 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號