Reputation: 25954
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:])
})
Upvotes: 11
Views: 15734
Reputation: 46413
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
Upvotes: 23
Reputation: 25954
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)
}
Upvotes: -2