In Go language, obtaining the file extension (suffix) is a common task, especially when handling file uploads, path parsing, or file type checking. Go's standard library path/filepath provides simple and efficient methods to achieve this functionality.
Using the filepath.Ext Function
Go's built-in filepath.Ext function is the most direct way to get the file extension. It accepts a file path string as a parameter and returns the file's extension, including the dot (.). If the file has no extension, it returns an empty string.
package main
import (
"fmt"
"path/filepath"
)
func main() {
filename := "example.txt"
ext := filepath.Ext(filename)
fmt.Println("Extension:", ext) // Output: .txt
}
Note: The filepath.Ext function only returns the part after the last dot, for example, file.tar.gz will return .gz, not .tar.gz. If you need to handle multi-part extensions, custom logic may be required.
Handling Cases Without Extensions
In practical applications, files may not have an extension, in which case filepath.Ext returns an empty string. You can handle this situation by checking the return value.
package main
import (
"fmt"
"path/filepath"
)
func main() {
filename := "README"
ext := filepath.Ext(filename)
if ext == "" {
fmt.Println("File has no extension")
} else {
fmt.Println("Extension:", ext)
}
}
Custom Function to Get Extension
If you need more flexible handling, such as ignoring the dot or dealing with multi-part extensions, you can write a custom function. Here is an example that returns the extension without the dot.
package main
import (
"fmt"
"path/filepath"
"strings"
)
func getExtension(filename string) string {
ext := filepath.Ext(filename)
// Remove the dot
return strings.TrimPrefix(ext, ".")
}
func main() {
filename := "document.pdf"
ext := getExtension(filename)
fmt.Println("Extension:", ext) // Output: pdf
}
Warning: When writing custom functions, pay attention to edge cases, such as empty strings or filenames containing multiple dots, to avoid errors.