Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

http.Request: get file name from url

Tags:

go

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:])
})
like image 504
Chris G. Avatar asked Jun 15 '17 08:06

Chris G.


1 Answers

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

Playground link

like image 164
Adrian Avatar answered Nov 13 '22 04:11

Adrian