September 2024

TIL: HTTP middleware for custom Go module paths

“Today I Learned” are instructions-focused posts about things I’ve learned.

I want to have my Go modules under my own domain, so instead of importing github.com/maragudk/example, I can import maragu.dev/example. Turns out it’s pretty easy.

Moving modules under a custom domain is often called “vanity” URLs, although I don’t think there’s so much vanity about it, as much as just good common sense. Having Go modules under your own domain allows you to control where your module code is actually hosted independently, so when Github is suddenly bought by some large corporation (oh wait, that already happened), you can move elsewhere easily if you like.

There are various blog posts out there already showing how to do this, so I’ll just summarize what happens when you call go get maragu.dev/httph.

Seeing a custom domain, go get requests maragu.dev/httph?go-get=1 and expects some specific HTML meta tags. It doesn’t even have to be a whole valid HTML page, as long as the meta tags are there, you’re good.

This is what they look like, in Go html/template format:

<meta name="go-import" content="{{ .Domain }}/{{ .Module }} git {{ .URLPrefix }}/{{ .Module }}">
<meta name="go-source" content="{{ .Domain }}/{{ .Module }}
  {{ .URLPrefix }}/{{ .Module }}
  {{ .URLPrefix }}/{{ .Module }}/tree/main{/dir}
  {{ .URLPrefix }}/{{ .Module }}/blob/main{/dir}/{file}#L{line}">

The go-import part is for the go get command directly, and the go-source part is for package documentation to link correctly to the source code.

And that’s basically it! I threw this functionality into some custom net/http middleware in my httph module of HTTP helpers, see the documentation here. In addition to serving the above HTML fragment, it also redirects non-go get requests to the correct location on Github. 😎

Enjoy!

Source: Vanity import paths in Go by Márk Sági-Kazár

A picture of me, Markus.

I’m Markus, a professional software consultant and developer. 🤓✨ Reach me at markus@maragu.dk.

Podcast on Apple Podcasts and Spotify. Streaming on Youtube. Subscribe to this blog by RSS or newsletter: