1 回答
TA贡献1862条经验 获得超6个赞
您正在做的是绑定要处理的完整路径。/location/{titan rolex}GetUser
您真正想要的是绑定/location/<every possible string>以由一个处理程序处理(例如LocationHandler)。
您可以使用标准库或其他路由器来做到这一点。我将介绍两种方式:
标准库:
import (
"fmt"
"net/http"
"log"
)
func locationHandler(w http.ResponseWriter, r *http.Request) {
name := r.URL.Path[len("/location/"):]
fmt.Fprintf(w, "Location: %s\n", name)
}
func main() {
http.HandleFunc("/location/", locationHandler)
log.Fatal(http.ListenAndServe(":8080", nil))
}
但是请注意,/location/<every possible string>/<some int>/<another string>以这种方式实现更复杂的路径(例如)会很乏味。
另一种方法是使用github.com/julienschmidt/httprouter,特别是如果您更频繁地遇到这些情况(并且路径更复杂)。
以下是您的用例的示例:
import (
"fmt"
"github.com/julienschmidt/httprouter"
"net/http"
"log"
)
func LocationHandler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
fmt.Fprintf(w, "Location: %s\n", ps.ByName("loc"))
}
func main() {
router := httprouter.New()
router.GET("/location/:loc", LocationHandler)
log.Fatal(http.ListenAndServe(":8080", router))
}
请注意,httprouter对处理程序使用稍微不同的签名。这是因为,如您所见,它还将这些参数传递给函数。
哦,还有一个注意事项,你可以直接http://localhost:8080/location/titan rolex用你的浏览器(或其他东西)点击 - 如果其他东西足够好,它会将 URLEncode 编码为http://localhost:8080/location/titan%20rolex.
- 1 回答
- 0 关注
- 240 浏览
添加回答
举报