From d4eebc634e4edaa9a8789fd7e3877b4d56423293 Mon Sep 17 00:00:00 2001 From: Ben Burwell Date: Fri, 13 Sep 2019 14:49:08 -0400 Subject: initial commit --- main.go | 83 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 main.go (limited to 'main.go') diff --git a/main.go b/main.go new file mode 100644 index 0000000..9d6f5cf --- /dev/null +++ b/main.go @@ -0,0 +1,83 @@ +package main + +import ( + "html/template" + "log" + "net/http" + "os" + "strings" + "time" + + "github.com/virtyx-technologies/readenv" +) + +func main() { + if err := run(); err != nil { + log.Fatal(err) + } +} + +type options struct { + Port string `env:"PORT"` + CacheExpiry time.Duration `env:"CACHE_EXPIRY"` + UpstreamTimeout time.Duration `env:"UPSTREAM_TIMEOUT"` + SourcehutUsername string `env:"SRHT_USERNAME"` + SourcehutToken string `env:"SRHT_TOKEN"` + GithubUsername string `env:"GITHUB_USERNAME"` + GithubToken string `env:"GITHUB_TOKEN"` + CanonicalPrefix string `env:"CANONICAL_PREFIX"` +} + +func run() error { + var opts options + if err := readenv.ReadEnv(&opts); err != nil { + return err + } + cache := &PackageCache{ + CanonicalPrefix: opts.CanonicalPrefix, + ExpireAfter: opts.CacheExpiry, + UpstreamTimeout: opts.UpstreamTimeout, + Logger: log.New(os.Stdout, "", log.LstdFlags), + Hosts: []RepoHost{ + Sourcehut{Username: opts.SourcehutUsername, Token: opts.SourcehutToken}, + Github{Username: opts.GithubUsername, Token: opts.GithubToken}, + }, + } + handler := handlePackage(cache) + return http.ListenAndServe(":"+opts.Port, handler) +} + +func handlePackage(pkgs *PackageCache) http.HandlerFunc { + tmpl, err := template.New("package").Parse(` + + + + + +

{{ .Name }}

+ + +`) + if err != nil { + return nil + } + return func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte(http.StatusText(http.StatusBadRequest))) + return + } + parts := strings.SplitN(r.URL.Path[1:], "/", 2) + pkg, ok := pkgs.Get(r.Context(), parts[0]) + if !ok { + w.WriteHeader(http.StatusNotFound) + w.Write([]byte(http.StatusText(http.StatusNotFound))) + return + } + log.Printf("pkg: %v", pkg) + tmpl.Execute(w, pkg) + } +} -- cgit v1.2.3