find the extension of a file in go

To find the extension of a file in Go, we can make use of the path/filepath package in combination with the strings package. The filepath package provides a Ext function which returns the extension (including the dot) of a file path. We can pass the file name to this function to get the extension.

Here's an example:

main.go
package main

import (
    "fmt"
    "path/filepath"
    "strings"
)

func main() {
    fileName := "example.txt"
    extension := filepath.Ext(fileName)
    extension = strings.ToLower(extension)
    
    fmt.Println(extension) // prints ".txt"
}
248 chars
16 lines

In the above example, we defined the file name as example.txt. We then call the filepath.Ext function on the file name to get the extension, and then convert it to lowercase using the strings.ToLower method. Finally, we print the extension using fmt.Println.

Note that the extension returned by filepath.Ext includes the dot, so we also convert it to lowercase using strings.ToLower to standardize the extension.

gistlibby LogSnag