我有以下小程序。它不接受编码双斜线 (%2F%2F),即使在使用 SkipClean 后,单编码斜线工作正常。
有人可以建议这里出了什么问题吗?
package main
import (
"fmt"
"net/http"
"github.com/gorilla/mux"
)
func main() {
r := mux.NewRouter().SkipClean(true).UseEncodedPath()
r.HandleFunc("/", hiHandler)
r.HandleFunc("/hi{*}", hiHandler).Methods("GET")
http.Handle("/", r)
http.ListenAndServe(":10801", nil)
}
func hiHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Hello world!")
}
#curl http://localhost:10801/hi%2Fds => 这有效#curl http://localhost:10801/hi%2F%2Fds => 这不是。给出永久移动错误。
最佳答案
诀窍是以稍微不同的方式运行服务器。
package main
import (
"fmt"
"github.com/gorilla/mux"
"log"
"net/http"
"time"
)
func main() {
r := mux.NewRouter().SkipClean(true).UseEncodedPath()
r.HandleFunc("/", hiHandler)
r.HandleFunc("/hi{*}", hiHandler).Methods("GET")
srv := &http.Server{
Handler: r,
Addr: "localhost:10801",
// Good practice: enforce timeouts for servers you create!
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
log.Fatal(srv.ListenAndServe())
}
func hiHandler(w http.ResponseWriter, r *http.Request) {
// Putting the match of {*} into the output
v := mux.Vars(r)
fmt.Fprint(w, "Hello world! ", v["*"])
}
curl http://localhost:10801/hi%2Fds
将输出 Hello world! %2Fds
curl http://localhost:10801/hi%2F%2Fds
将输出 Hello world! %2F%2Fds
.
关于go - 即使使用 SkipClean 后也不接受双斜线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63370135/