1. 19

  2. 5

    Yet the new fs API doesn’t support contexts at all, so you have to embed them in your fs struct.

    1. 9

      The io package in general doesn’t support contexts (io.Reader and io.Writer are examples of this), and they’re a bit of a pain to adapt. In particular, file IO on Linux is blocking, so there’s no true way to interrupt it with a context. Most of the adapters I’ve seen use ctx.Deadline() to get the deadline, but even that isn’t good enough because a context can be cancelled directly. I’d imagine that’s why it’s not in the fs interfaces.

      For every Reader/Writer that doesn’t support Context directly, you need a goroutine running to adapt it which is not ideal. There is some magic you can do with net.Conn (or rather *net.TCPConn) because of SetDeadline, but even those would need a goroutine and other types like fs.File (and *os.File) would leave the Read or Write running in the background until it completes which opens you up to all sorts of issues.

      1. 1

        You can you use the fs.FS interface it to implement something like a frontend for WebDav, “SSH filesystem”, and so forth, where the need for a context and timeouts is a bit more acute than just filesystem access. This actually also applies to io.Reader etc.

      2. 1

        I’m not entirely sure why the new fs package API doesn’t support contexts, but you could potentially write a simple wrapper for that same API which does, exposing a new API with methods like WithContext, maybe?

        Especially considering what the documentation for context states:

        Contexts should not be stored inside a struct type, but instead passed to each function that needs it.

        But ideally I’d like to see context supported in the new fs package too.