Thomas Payne - Go code snippets

Go code snippets

fragments of Go code which don't deserve their own library

return the file path for the last modified file which matches the provided regex

func GetLatestModifiedFileWhichMatchesRegex(dir string, regex *regexp.Regexp) (string, error) {
	var ret *struct {
		time time.Time
		path string
	}

	entries, err := os.ReadDir(dir)
	if err != nil {
		return "", err
	}

	for _, entry := range entries {
		if entry.IsDir() || !regex.MatchString(entry.Name()) {
			continue
		}

		path := filepath.Join(dir, entry.Name())

		if info, err := os.Stat(path); err != nil {
			return "", err
		} else {
			if ret == nil || ret.time.Before(info.ModTime()) {
				ret = &struct {
					time time.Time
					path string
				}{
					time: info.ModTime(),
					path: path,
				}
			}
		}
	}

	if ret == nil {
		return "", fmt.Errorf("no files match regex")
	}

	return ret.path, nil
}

open a json file and parse it returning errors

var s Structure
if fd, err := os.Open(path); err != nil {
	return nil, err
} else {
	if err := json.NewDecoder(fd).Decode(&s); err != nil {
        return nil, err
	}
}