2 回答

TA貢獻1893條經(jīng)驗 獲得超10個贊
如果您不想使用任何第三方庫,則必須自己處理路徑的解析。
首先,您可以這樣做:
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
page := r.URL.Path[1:]
// do whatever logic you want
// mind that the page could be "multi/level/path/" as well
})

TA貢獻1853條經(jīng)驗 獲得超9個贊
您可以使用 http.HandleFunc。在這個函數(shù)中,以斜線結(jié)尾的模式定義了一個子樹。您可以使用模式“/page/”注冊處理程序函數(shù),如下例所示。
package main
import (
"net/http"
"fmt"
)
func handler(w http.ResponseWriter, r *http.Request) {
if is_valid_page(r.URL) {
fmt.Fprint(w, "This is a valid page")
} else {
w.WriteHeader(http.StatusNotFound)
fmt.Fprint(w, "Error 404 - Page not found")
}
}
func is_valid_page(page string) {
// check here if page is valid from url
}
func main() {
http.HandleFunc("/page/", handler)
http.ListenAndServe(":8080", nil)
}
您可以在這里找到更多信息:https ://golang.org/pkg/net/http/#ServeMux
- 2 回答
- 0 關(guān)注
- 124 瀏覽
添加回答
舉報