Mastering Go File Path Handling with strings.LastIndex
This article explains how to efficiently use Go's strings.LastIndex function to extract a directory from a file path, verify its existence, and create the parent directory when missing, providing a concise alternative to dedicated path libraries.
In Go development, handling file paths is a common task. This article demonstrates using strings.LastIndex to extract a directory from a file path and ensure the parent directory exists, creating it if necessary.
Background: strings.LastIndex
The strings.LastIndex function returns the index of the last occurrence of a substring within a string, or -1 if the substring is absent, making it ideal for locating the final path separator.
func LastIndex(s, substr string) intExample: checkCreateDbFile
func checkCreateDbFile(file string) error {
// Get directory path
dir := file[:strings.LastIndex(file, "/")]
// Check if directory exists
if _, err := os.Stat(dir); os.IsNotExist(err) {
// Create directory and its parents
if err := os.MkdirAll(dir, os.ModePerm); err != nil {
logrus.Errorf("create db file dir error: %v", err)
return err
}
}
return nil
}Key Points
Using strings.LastIndex to locate the last "/" and slice the path, avoiding extra path‑handling libraries.
Directory existence check should employ os.IsNotExist(err) rather than comparing os.ErrExist with the error.
Directory creation with os.MkdirAll and os.ModePerm ensures the full directory tree is created with appropriate permissions.
Conclusion
The strings.LastIndex method showcases the power of Go's standard library for routine tasks, reducing code complexity while improving readability and maintainability when handling file and directory operations.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Ops Development & AI Practice
DevSecOps engineer sharing experiences and insights on AI, Web3, and Claude code development. Aims to help solve technical challenges, improve development efficiency, and grow through community interaction. Feel free to comment and discuss.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
