gpt4 book ai didi

http - 如何让 Go 的 net/http 包停止删除双斜杠?

转载 作者:IT王子 更新时间:2023-10-29 01:40:51 25 4
gpt4 key购买 nike

考虑以下非常基本的“net/http”程序:

package main

import (
"net/http"
"log"
)

func entry(w http.ResponseWriter, req *http.Request) {
log.Println(req.URL.Path)
path := []byte(req.URL.Path)
w.Write(path)
}

func main() {
http.HandleFunc("/", entry)
err := http.ListenAndServe("localhost:10000", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}

访问URL时,http://localhost:10000/a//bDefaultServerMux,也就是默认的HandleFunc()ListenAndServe() 使用,将其重定向到 /a/b,有效地删除了双斜杠。

documentation for ServerMux确实指定它“清理”URL 请求:

ServeMux also takes care of sanitizing the URL request path, redirecting any request containing . or .. elements or repeated slashes to an equivalent, cleaner URL.

但如果我不想这样做怎么办?我有一个场景,其中 // != / 在我的 URL 中。我可以找到另一个解决方案。但是有没有办法仍然使用 Go 的“net/http”包,同时它不会像这样清理我的 URL?最好尽可能少地重写。

(我可能会找到一个不同于 /// 不同的解决方案,因为我可能对 ServerMux 的其他功能感到满意> 提供(如果解决方案需要我使用另一个多路复用器),但现在我很好奇是否有 Go 的标准“net/http”包的解决方案。)

最佳答案

使用 gorilla mux 使用 url 路由服务器。默认情况下,DefaultSeveMux 使用 Clean它针对各种不需要的字符修改 url。这就是当您使用 // 双斜杠时 url 发生变化的原因。

func Clean(path string) string

如果您不想清理 url。 Gorilla mux 提供了一个 SkipClean() 方法,当设置为 true 时。它不会清理 url。

func (r *Router) SkipClean(value bool) *Router {
r.skipClean = value
return r
}

SkipClean() 的 gorilla mux 文档中提到:

SkipClean defines the path cleaning behaviour for new routes. The initial value is false. Users should be careful about which routes are not cleaned When true, if the route path is "/path//to", it will remain with the double slash. This is helpful if you have a route like: /fetch/http://xkcd.com/534/ When false, the path will be cleaned, so /fetch/http://xkcd.com/534/ will become /fetch/http/xkcd.com/534

关于http - 如何让 Go 的 net/http 包停止删除双斜杠?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51908277/

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