I Spy Code - GO

Get file name extension used by path

Question:

How do the get the file name extension used by path in golang?

Answer:

The function filepath.Ext() returns the file name extension used by path.

Here is a golang example that shows how to get a file name extension from its path :

Source: (example.go)

package main
 
import (
   "fmt"
   "path/filepath"
)
 
func main() {
   extension := filepath.Ext("/tmp/hello.go")
   fmt.Println("Extension 1:", extension)
 
   extension = filepath.Ext("./hello.jpg")
   fmt.Println("Extension 2:", extension)
}
 

Output:

$ go run example.go
Extension 1: .go
Extension 2: .jpg

References:

https://golang.org/pkg/path/filepath/#Ext