| 1 | /** |
| 2 | * `go get g1t.sh/<workspace>/<repo>[/<package>]`: Go asks the address with |
| 3 | * `?go-get=1` and reads where the module's code is from a `go-import` meta |
| 4 | * tag. Every repository answers, public or private, without looking it up: |
| 5 | * the answer only says where git would find it, and git then asks for |
| 6 | * credentials (GOPRIVATE and .netrc) as it would for a clone. |
| 7 | */ |
| 8 | |
| 9 | const WORKSPACE = /^[a-z0-9](?:[a-z0-9]|-(?=[a-z0-9])){0,38}$/; |
| 10 | const REPO = /^[a-z0-9._-]{1,100}$/; |
| 11 | |
| 12 | /** The page Go reads for `url`, or null when it is not a go-get request for a repository. */ |
| 13 | export function goImport(url: URL): string | null { |
| 14 | if (url.searchParams.get("go-get") !== "1") return null; |
| 15 | const [workspace, rawRepo] = url.pathname.split("/").filter(Boolean); |
| 16 | if (!workspace || !rawRepo) return null; |
| 17 | const repo = rawRepo.replace(/\.git$/, ""); |
| 18 | if (!WORKSPACE.test(workspace) || !REPO.test(repo) || repo.startsWith(".") || workspace === "-" || repo === "-") return null; |
| 19 | const host = url.host; |
| 20 | const prefix = `${host}/${workspace}/${repo}`; |
| 21 | const home = `${url.protocol}//${prefix}`; |
| 22 | return [ |
| 23 | "<!doctype html>", |
| 24 | "<html><head>", |
| 25 | `<meta name="go-import" content="${prefix} git ${home}.git">`, |
| 26 | `<meta name="go-source" content="${prefix} ${home} ${home}/tree/HEAD{/dir} ${home}/blob/HEAD{/dir}/{file}#L{line}">`, |
| 27 | "</head><body>", |
| 28 | `go get ${prefix}`, |
| 29 | "</body></html>", |
| 30 | "", |
| 31 | ].join("\n"); |
| 32 | } |