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.

Ops Development & AI Practice
Ops Development & AI Practice
Ops Development & AI Practice
Mastering Go File Path Handling with strings.LastIndex

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) int

Example: 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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Backend DevelopmentGoFile Pathos.MkdirAllos.Statstrings.LastIndex
Ops Development & AI Practice
Written by

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.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.