Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用标准库的函数处理程序GoLang_Go_Gorilla_Mux_Url Parsing - Fatal编程技术网

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

使用标准库的函数处理程序GoLang,go,gorilla,mux,url-parsing,Go,Gorilla,Mux,Url Parsing,我有一个类似于events/{id}的端点和它的处理程序。如何在不使用Gorilla/Mux的情况下获取{id}。可以实现这一目标的GoLang内置替代方案有哪些?需要在没有gorilla/Mux或其他第三方库的情况下执行此操作。我知道这可以用mux.Vars来完成,但不能在这里使用。您可以从/events/之后开始获取字符串片段: func eventHandler(w http.ResponseWriter, r *http.Request) { id := r.URL.Path[l

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

您可以从
/events/
之后开始获取字符串片段:

func eventHandler(w http.ResponseWriter, r *http.Request) {
    id := r.URL.Path[len("/events/"):]
    w.Write([]byte("The ID is " + id))
}

func main() {
    http.HandleFunc("/events/", eventHandler)
}

如果您已经设法将流量定向到处理程序,那么您只需自己解析URL路径即可:

func HandlerFunc(w http.ResponseWriter,request*http.request){
段:=strings.Split(request.URL.Path,“/”)
//如果路径为/events/id,则段[2]将具有该id
}
Request.URL.Path已被URL解码,因此如果您的参数可能包含斜杠,请使用,而不是:

segments:=strings.Split(r.RequestURI,“/”)
对于i:=范围段{
变量错误
段[i],err=url.PathUnescape(段[i])
如果错误!=零{
http.Error(w,err.Error(),http.StatusBadRequest)
返回
}
}
id:=strings.TrimPrefix(req.URL.Path,“/events/”)