Created
January 2, 2024 16:04
-
-
Save lukechampine/6bbea2268404d6ad74122e93fef30a9b to your computer and use it in GitHub Desktop.
Vanity Go import server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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