Golang : Get remaining text such as id or filename after last segment in URL path
Problem:
Retrieving the last segment/part or the remaining text after a slash in the URL or filename in a path can be challenging for newbies in programming. Such as:
123456
from //www.socketloop.com/123456
or
image.png
from c:\windows\image.png
How to extract the desired information from an URL or file path?
Solution:
This is known as extracting the base of a URL or file path. Use the path
package base()
function to extract the last segment or remaining text after the last slash.
Here you go!
package main
import (
"fmt"
"path"
"path/filepath"
)
func main() {
url := "http://www.abcdef.com/12345678"
base := path.Base(url)
fmt.Println(base)
// NOTE: filepath.Base() will WORK with `\`
// provided this program runs on Windows platform
// if this program executes on Non-windows or play.golang.org
// it will show the entire string instead of
// the desire image.exe
// IT IS NOT A BUG!
windowsFilePath := `c:\windows\image.exe`
imageFile := filepath.Base(windowsFilePath)
fmt.Println(imageFile)
}
Output:
12345678
image.exe
See also : Golang : Match strings by wildcard patterns with filepath.Match() function
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+13.5k Golang : invalid character ',' looking for beginning of value
+14.9k Golang : Login and logout a user after password verification and redirect example
+3.8k Golang : Intercept, inject and replay HTTP traffics from web server
+21.4k Golang : Find biggest/largest number in array
+5.1k Golang : Check if one string(rune) is permutation of another string(rune)
+13.5k Golang : Check if a string contains multiple sub-strings in []string?
+24.1k Golang : Convert CSV data to JSON format and save to file
+6.7k Golang : Get curl -I or head data from URL example
+19.1k Golang : Convert Unix timestamp to UTC timestamp
+22.1k Golang : Call function from another package
+7.7k Golang : Function wrapper that takes arguments and return result example
+7.2k Golang : Format strings to SEO friendly URL example