2017-07-30 62 views
0

我正在創建一個Go Web應用程序,我需要處理URL/person /(any_name)這樣的URL。作爲Golang的新手,我不知道如何去做。請幫幫我。如何在Golang中處理動態URL

+1

大家好,歡迎堆棧溢出。您的問題沒有足夠的信息來了解問題,因此我們需要查看您迄今爲止所嘗試的內容。如果您剛接觸Go,您可能需要閱讀[A Tour Of Go](https://tour.golang.org/list),[Effective Go](https://golang.org/doc/) effective_go.html)和[Go By Example](https://gobyexample.com/)。 – Schwern

+0

「處理URL」是什麼意思?你有什麼嘗試?你使用路由器嗎?哪一個? – Flimzy

+0

在提出任何問題之前,請先閱讀官方文檔。 – Warrior

回答

0

如果你看看這個頁面https://golang.org/doc/articles/wiki/有一些我認爲你在追求的例子。

您想要一個名爲person的處理程序,然後提取(any_name)並相應地爲每個人處理它。其中一個例子顯示瞭如何使用同樣的原則標題。

func viewHandler(w http.ResponseWriter, r *http.Request) { 
    title := r.URL.Path[len("/view/"):] 
    p, _ := loadPage(title) 
    t, _ := template.ParseFiles("view.html") 
    t.Execute(w, p) 
} 

而不是/你有/人/和標題是什麼(any_name)是你的情況。

r.URL.Path[len("/view/"):]將採取一切從r.URL.Path,但開始len("/view/")字節進入切片。

1

你應該看看使用大猩猩/多路複用器包你正在做什麼。 一個從包GitHub的摘錄顯示https://github.com/gorilla/mux

r := mux.NewRouter() 
r.HandleFunc("/products/{key}", ProductHandler) 
r.HandleFunc("/articles/{category}/", ArticlesCategoryHandler) 
r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler)