initial commit

This commit is contained in:
Serge Zaitsev
2018-09-19 11:20:09 +02:00
parent 95a937ef2c
commit ce767e10ee
11 changed files with 918 additions and 1 deletions

103
cmd/gomodproxy/main.go Normal file
View File

@@ -0,0 +1,103 @@
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"log"
"net"
"net/http"
"os"
"os/signal"
"path/filepath"
"strings"
"time"
"github.com/sixt/gomodproxy/pkg/api"
)
func prettyLog(v ...interface{}) {
s := ""
msg := ""
if len(v)%2 != 0 {
msg = fmt.Sprintf("%s", v[0])
v = v[1:]
}
s = fmt.Sprintf("%20s ", msg)
for i := 0; i < len(v); i = i + 2 {
s = s + fmt.Sprintf("%v=%v ", v[i], v[i+1])
}
log.Println(s)
}
func jsonLog(v ...interface{}) {
entry := map[string]interface{}{}
if len(v)%2 != 0 {
entry["msg"] = v[0]
v = v[1:]
}
for i := 0; i < len(v); i = i + 2 {
entry[fmt.Sprintf("%v", v[i])] = v[i+1]
}
json.NewEncoder(os.Stdout).Encode(entry)
}
type listFlag []string
func (f *listFlag) String() string { return strings.Join(*f, " ") }
func (f *listFlag) Set(s string) error { *f = append(*f, s); return nil }
func main() {
gitPaths := listFlag{}
addr := flag.String("addr", ":0", "http server address")
verbose := flag.Bool("v", false, "verbose logging")
json := flag.Bool("json", false, "json structured logging")
dir := flag.String("dir", filepath.Join(os.Getenv("HOME"), ".gomodproxy"), "cache directory")
flag.Var(&gitPaths, "git", "list of git settings")
flag.Parse()
ln, err := net.Listen("tcp", *addr)
if err != nil {
log.Fatal("net.Listen:", err)
}
defer ln.Close()
fmt.Println("Listening on", ln.Addr())
options := []api.Option{}
if *verbose || *json {
if *json {
options = append(options, api.Log(jsonLog))
} else {
options = append(options, api.Log(prettyLog))
}
}
for _, path := range gitPaths {
kv := strings.SplitN(path, "=", 2)
if len(kv) != 2 {
log.Fatal("bad git path:", path)
}
options = append(options, api.Git(kv[0], kv[1]))
}
options = append(options, api.Memory(), api.CacheDir(*dir))
sigc := make(chan os.Signal, 1)
signal.Notify(sigc, os.Interrupt)
srv := &http.Server{Handler: api.New(options...)}
go func() {
if err := srv.Serve(ln); err != nil {
log.Fatal(err)
}
}()
<-sigc
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
srv.Shutdown(ctx)
}