gpt4 book ai didi

go - 使用标准库的函数处理程序 GoLang

转载 作者:行者123 更新时间:2023-12-01 22:38:47 25 4
gpt4 key购买 nike

我有一个像 events/{id} 这样的端点和它的处理程序。我怎样才能得到{id}不使用 Gorilla/Mux。可以实现这一目标的 GoLang 内置替代方案有哪些?需要在没有 gorilla/Mux 或其他第三方库的情况下执行此操作。我知道这可以用 mux.Vars 完成,但不能在这里使用。

最佳答案

如果您已经设法将流量定向到您的处理程序,那么您可以简单地自己解析 URL 路径:

func HandlerFunc(w http.ResponseWriter, request *http.Request) {
segments := strings.Split(request.URL.Path, "/")
// If path is /events/id, then segments[2] will have the id
}

Request.URL.Path 已经被 URL 解码,所以如果您的参数可能包含斜杠,请使用 Request.RequestURIurl.PathUnescape反而:

segments := strings.Split(r.RequestURI, "/")
for i := range segments {
var err error
segments[i], err = url.PathUnescape(segments[i])
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
}

关于go - 使用标准库的函数处理程序 GoLang,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59853832/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com