Statically Typed Context

117 views
Skip to first unread message

Adam Berkan

unread,
Apr 9, 2022, 11:30:00 PM4/9/22
to golang-nuts
Khan Academy Engineering Blog Post:  https://blog.khanacademy.org/statically-typed-context-in-go/

Khan Academy has been porting our backend from Python to Go.  One thing we hoped to get from it was fewer uses of implicit global resources and request data.  We looked at explicitly passing everything as parameters, or hiding things in the context.

In the end we decided to extend the context interface to provide access to these global & request elements.  This gives us strongly typed interfaces, with less verbosity than writing every parameter out.

func DoTheThing(
    ctx interface {
        context.Context
        RequestContext
        DatabaseContext
        HttpClientContext
        SecretsContext
        LoggerContext
    },
    thing string,
) {...}

I've written a whole blog post about the idea, our motivations, and our experience with it.  There's also some sample code available showing the different approaches we considered: https://github.com/Khan/typed-context/

I realize this is not a wholly uncontroversial idea, but I'd appreciate any feedback.

Adam

Christian von Kietzell

unread,
Apr 10, 2022, 4:31:23 AM4/10/22
to golan...@googlegroups.com
Hi Adam,

thanks for that article. I really like the idea and will try it on one of my
next projects.


Cheers,
Chris
> --
> You received this message because you are subscribed to the Google Groups "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
> To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/2a1928ab-051b-492b-b4a1-154602d4067cn%40googlegroups.com.


--
Nothing to see here. Move along.
Reply all
Reply to author
Forward
0 new messages