Retrieving file timestamps in Go

Recently, a friend of mine needed to get the creation time of a file in a Go project. There’s os.Stat , so how hard can it be, right? os.Stat returns fs.FileInfo which is an interface with six methods: type FileInfo interface { Name() string // base name of the file Size() int64 // length in bytes for regular files; [..] Mode() FileMode // file mode bits ModTime() time.Time // modification time IsDir() bool // abbreviation for Mode().IsDir() Sys() any // underlying data source (can return nil) } Time of last modification (mtime) is the only time reported by this interface, though. There is no time of last access (atime), creation (btime), nor status change (ctime). ...

19 May 2024 · 906 words

Type for a context value in Go

Using context values in Go appears, at first sight, very trivial and easily understood. There are pitfalls, though. For instance, what type to use for the key? ❯ go doc context WithValue package context // import "context" func WithValue(parent Context, key, val any) Context WithValue returns a copy of parent in which the value associated with key is val. Use context Values only for request-scoped data that transits processes and APIs, not for passing optional parameters to functions. The provided key must be comparable and should not be of type string or any other built-in type to avoid collisions between packages using context. Users of WithValue should define their own types for keys. To avoid allocating when assigning to an interface{}, context keys often have concrete type struct{}. Alternatively, exported context key variables' static type should be a pointer or interface. This whole article exists because of this: ...

8 December 2023 · 602 words

Simple Unix-like authorization with Go

Modern complex projects often require sophisticated access-control functionality, like Identity and Access Management (IAM ) systems. Sometimes, however there are cases where simple solutions might just cut it. Let’s cover one of these cases. Say we’re working on a system for publishing articles, allowing discussion below each article, with the following requirements: Moderators can edit all articles and comments Authors can create articles and edit only those created by themselves Users can read articles and post comments about them Any user-type can edit and delete their own profile We could define different user-levels as a bit-mask and store that alongside user’s information (e.g. users table in the database): ...

3 September 2023 · 637 words