summaryrefslogblamecommitdiff
path: root/main.go
blob: f09ccce3951c8e333175647e2094f9cfe33c9ea6 (plain) (tree)






























































                                                                                       
package main

import (
	"fmt"
	"log"
	"net/http"

	"radr.ee/cgit-go-import/cgitrc"
)

type importRepo struct {
	prefix   string
	cloneURL string
}

var (
	handlers = make(map[string]http.Handler)
)

func serveStatus(w http.ResponseWriter, status int) {
	w.WriteHeader(status)
	w.Write([]byte(http.StatusText(status)))
}

func handleRequest(w http.ResponseWriter, r *http.Request) {
	if r.Method == "HEAD" {
		return
	}
	if r.Method != "GET" || r.URL.RawQuery != "go-import=1" {
		serveStatus(w, 404)
		return
	}
	handler, ok := handlers[r.URL.Path]
	if ok {
		handler.ServeHTTP(w, r)
	} else {
		serveStatus(w, 404)
	}
}

func createRepoHandler(cfg *cgitrc.Config, r *cgitrc.Repo) http.Handler {
	body := []byte(fmt.Sprintf(
		"<head><meta name=\"go-import\" content=\"radr.ee/%s git %s\"></head>",
		r.URL,
		cfg.ResolveRepoCloneURL(r),
	))
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/html")
		w.Write(body)
	})
}

func main() {
	cfg, err := cgitrc.Open("/etc/cgitrc")
	if err != nil {
		log.Fatal(err)
	}
	for _, r := range cfg.Repos {
		handlers["/"+r.URL] = createRepoHandler(cfg, r)
	}

	http.ListenAndServe(":8080", http.HandlerFunc(handleRequest))
}