Search code examples
gocase-sensitive

Case insensitive HasSuffix in Go


I am looking for specific file types from a directory listing and use HasSuffix to do the comparision looking for a few specific file types. I would like to make this comparison case insensitive.

Is there a way to add EqualFold or another case insensitive comparison to the HasSuffix function?


Solution

  • You could just use

    if strings.HasSuffix(strings.ToLower(s), "suffix") {
        // do something 
    }
    

    You can also write your own wrapper function:

    func hasSuffix(s, suffix string, caseSensitive bool) bool {
        if caseSensitive {
            return strings.HasSuffix(s, suffix)
        }
        return strings.HasSuffix(strings.ToLower(s), suffix)
    }
    

    For file names or paths you can use (see answer of PeterSO):

    if strings.ToLower(filepath.Ext(s)) == ".fileending" {
        // do something
    }