英文:
http.Request: get file name from url
问题
如何从以下请求中获取文件名one.json
:http://localhost/slow/one.json
?
我只需要从URL中提供这个文件和其他文件。这是一个我需要以非常慢的速度响应的测试服务器。
http.HandleFunc("/slow/", func(w http.ResponseWriter, r *http.Request) {
log.Println("Slow...")
log.Println(r.URL.Path[1:])
time.Sleep(100 * time.Millisecond)
http.ServeFile(w, r, r.URL.Path[1:])
})
英文:
How do I get only the file name one.json
from the following request: http://localhost/slow/one.json
?
I just need to serve this file and others from the url? This is a test server that I need to respond very slow.
http.HandleFunc("/slow/", func(w http.ResponseWriter, r *http.Request) {
log.Println("Slow...")
log.Println(r.URL.Path[1:])
time.Sleep(100 * time.Millisecond)
http.ServeFile(w, r, r.URL.Path[1:])
})
答案1
得分: 19
我相信你正在寻找path.Base
函数:"Base函数返回路径的最后一个元素。"
r, _ := http.NewRequest("GET", "http://localhost/slow/one.json", nil)
fmt.Println(path.Base(r.URL.Path))
// 输出:one.json
英文:
I believe you are looking for path.Base
: "Base returns the last element of path."
r,_ := http.NewRequest("GET", "http://localhost/slow/one.json", nil)
fmt.Println(path.Base(r.URL.Path))
// one.json
答案2
得分: -1
创建了两个文件夹 slow
和 fast
,然后我使用了以下代码:
package main
import (
"log"
"net/http"
"time"
"fmt"
)
func main() {
h := http.NewServeMux()
h.HandleFunc("/fast/", func(w http.ResponseWriter, r *http.Request) {
fmt.Println(r.URL.Path[1:])
time.Sleep(100 * time.Millisecond)
http.ServeFile(w, r, r.URL.Path[1:])
})
h.HandleFunc("/slow/", func(w http.ResponseWriter, r *http.Request) {
fmt.Println(r.URL.Path[1:])
time.Sleep(6000 * time.Millisecond)
http.ServeFile(w, r, r.URL.Path[1:])
})
h.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(404)
})
err := http.ListenAndServe(":8080", h)
log.Fatal(err)
}
英文:
Created two folders slow
and fast
and then I ended up using the following:
package main
import (
"log"
"net/http"
"time"
"fmt"
)
func main() {
h := http.NewServeMux()
h.HandleFunc("/fast/", func(w http.ResponseWriter, r *http.Request) {
fmt.Println(r.URL.Path[1:])
time.Sleep(100 * time.Millisecond)
http.ServeFile(w, r, r.URL.Path[1:])
})
h.HandleFunc("/slow/", func(w http.ResponseWriter, r *http.Request) {
fmt.Println(r.URL.Path[1:])
time.Sleep(6000 * time.Millisecond)
http.ServeFile(w, r, r.URL.Path[1:])
})
h.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(404)
})
err := http.ListenAndServe(":8080", h)
log.Fatal(err)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论