Skip to content

Instantly share code, notes, and snippets.

@lukechampine
Created January 2, 2024 16:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lukechampine/6bbea2268404d6ad74122e93fef30a9b to your computer and use it in GitHub Desktop.
Save lukechampine/6bbea2268404d6ad74122e93fef30a9b to your computer and use it in GitHub Desktop.
Vanity Go import server
package main
import (
"flag"
"html/template"
"log"
"net/http"
"strings"
)
var tmpl = template.Must(template.New("main").Parse(`<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="go-import" content="{{.Domain}}/{{.PkgRoot}} git https://{{.VCS}}/{{.RepoRoot}}">
<meta http-equiv="refresh" content="0; url=https://godoc.org/{{.Domain}}{{.ImportPath}}">
</head>
<body>
Redirecting to docs at <a href="https://godoc.org/{{.Domain}}{{.ImportPath}}">godoc.org/{{.Domain}}{{.ImportPath}}</a>...
</body>
</html>
`))
func main() {
domain := flag.String("domain", "", "vanity domain, e.g. foo.com")
vcs := flag.String("vcs", "", "vcs URL, e.g. github.com/foo")
addr := flag.String("addr", ":8080", "host:port to listen on")
flag.Parse()
if *domain == "" {
log.Fatal("Missing required flag: -domain")
}
if *vcs == "" {
log.Fatal("Missing required flag: -vcs")
}
log.Printf("Listening on %v...", *addr)
log.Fatal(http.ListenAndServe(*addr, http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodGet {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
root := strings.Split(req.URL.Path, "/")[1]
w.Header().Set("Cache-Control", "public, max-age=300")
tmpl.Execute(w, struct {
Domain string
VCS string
PkgRoot string
RepoRoot string
ImportPath string
}{
Domain: *domain,
VCS: *vcs,
PkgRoot: root,
RepoRoot: root,
ImportPath: req.URL.Path,
})
})))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment