all repos — goget @ 7732a61b7775ba7448e1c69e0d577577f1e228f2

returns a go-import meta tag

main.go (view raw)

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
package main

import (
	"flag"
	"fmt"
	"log"
	"net/http"
	"os"
	"path"
)

type config struct {
	prettyurl string
	giturl string
	addr string
}

func logger(h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		h.ServeHTTP(w, r)

		uri := r.URL.String()
		method := r.Method
		ua := r.UserAgent()
		log.Printf("%s: %s -- %s", method, uri, ua)
	})
}

func (c *config) goget(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("content-type", "text/html")

	if r.URL.Query().Get("go-get") == "1" {
		pretty := path.Join(c.prettyurl, r.URL.Path)
		content := path.Join(c.giturl, r.URL.Path)
		fmt.Fprintf(
			w, `<head><meta name="go-import" content="%s git https://%s"></head>`,
			pretty, content,
		)
	} else {
		http.Redirect(w, r, "https://"+c.giturl, http.StatusTemporaryRedirect)
	}
	return
}

func main() {
	cfg := config{}
	flag.StringVar(&cfg.prettyurl, "pretty-url", "", "pretty url for your go module")
	flag.StringVar(&cfg.giturl, "git-url", "", "actual git url of your go module")
	flag.StringVar(&cfg.addr, "addr", "0.0.0.0:6868", "listen address")
	flag.Parse()

	if cfg.giturl == "" || cfg.prettyurl == "" {
		fmt.Println("goget: required options --pretty-url and --git-url")
		os.Exit(1)
	}

	mux := http.NewServeMux()
	log.Printf("starting server on %s", cfg.addr)
	mux.Handle("/", logger(http.HandlerFunc(cfg.goget)))
	log.Fatal(http.ListenAndServe(cfg.addr, mux))
}