Go vanity imports with Caddy
Go uses the full URL to a repo to fetch it with go get, i.e. go get github.com/username/module fetches it from exactly that repo.
It can be nice not to tie yourself to a specific repository host. The go
command always fetches using a query string of go-get=1.
We can make use of this in Caddy to return an HTML meta tag understood by go get to point at the actual repo; or otherwise redirect to the module’s
documentation on pkg.go.dev.
I define a snippet in my Caddyfile to make reusable configuration:
(go_module) {
handle /{args[0]} {
redir * /{args[0]}/
}
handle /{args[0]}/* {
@goget query go-get=1
handle @goget {
header Content-Type "text/html; charset=utf-8"
respond <<HTML
<head><meta name="go-import" content="{host}/{args[0]} git {args[1]}">
HTML
}
handle {
redir https://pkg.go.dev/{host}/{args[0]}{uri}
}
}
}
And then in a virtual host I can use this snippet as many times as I want to add new modules.
example.com {
import go_module my-module https://codeberg.org/username/my-module
}
Now go get example.com/my-module will, in the background, actually fetch it
from https://codeberg.org/username/my-module. If you decide to move the repo
elsewhere, nobody needs to update their imports.