Vanity Go Import Paths for Caddy 2

Maybe the following is useful for somebody else, too.

The general idea is to have a Go package at example.com/mypackage whose VCS is at https://github.com/exampleuser/mypackage.

For Caddy 1, there is a dedicated module: GitHub - zikes/gopkg: A Caddy plugin to add gopkg-like functionality to your own web sites. However, it is somewhat unmaintained nowadays. Also there is no equivalent module for Caddy 2 around. That kept me on Caddy 1… until today.

My first impulse was to re-implement the functionality as a Caddy 2 module. When I immersed in the documentation to familiarize myself with extending Caddy 2 I became aware that I could express everything I need with the standard modules and building blocks in a Caddyfile. Here is what I came up with.

example.com {
	root * /var/html/www
	file_server

	route /mypackage {
		@goget query go-get=1
		respond @goget `<meta name="go-import" content="example.com/mypackage git https://github.com/exampleuser/mypackage">`

		redir https://pkg.go.dev/example.com/mypackage
	}
}

Note that the route has the effect of overriding the Caddyfile’s default directive order, because otherwise, the redir would always happen before the respond.

3 Likes

does this actually work? the redir just catches everything.

root@46890d05369a:/go# go get -v go.xsfx.dev/logginghandler
package go.xsfx.dev/logginghandler: unrecognized import path "go.xsfx.dev/logginghandler": https fetch: Get "https://go.xsfx.dev/logginghandler?go-get=1": EOF
root@46890d05369a:/go# go get -v go.xsfx.dev/logginghandler
package go.xsfx.dev/logginghandler: unrecognized import path "go.xsfx.dev/logginghandler": parse https://go.xsfx.dev/logginghandler?go-get=1: no go-import meta tags ()

here my caddyfile:

go.xsfx.dev {
        @goget query go-get=1
        respond @goget `<meta name="go-import" content="{host}{path} git https://git.xsfx.dev/xsteadfastx{path}">`
        redir https://pkg.go.dev/{host}{path}
}

can it be that the directive order changed? when i add a

{
        order respond before redir
}

in the global section it works. but is this right?

@xsteadfastx that’s the purpose of the route, it forces a particular directive order.

this really helped me understanding it. my bad :slight_smile: works now!