github.com/sirkon/goproxy@v1.4.8/examples/goproxy/main.go (about) 1 //go:generate bash build/generate.sh 2 3 package main 4 5 import ( 6 "context" 7 "flag" 8 "fmt" 9 "net/http" 10 "os" 11 "os/signal" 12 "syscall" 13 "time" 14 15 "github.com/rs/zerolog" 16 gitlab2 "github.com/sirkon/gitlab" 17 18 "github.com/sirkon/goproxy" 19 "github.com/sirkon/goproxy/plugin/gitlab" 20 "github.com/sirkon/goproxy/plugin/vcs" 21 ) 22 23 var listen string 24 var cacheDir string 25 var gitlabAPIURL string 26 27 func init() { 28 flag.StringVar(&cacheDir, "cache-dir", "", "go modules cache dir") 29 flag.StringVar(&gitlabAPIURL, "gitlab-api-url", "", "gitlab host to get modules from") 30 flag.StringVar(&listen, "listen", "0.0.0.0:8081", "service listen address") 31 flag.Parse() 32 } 33 34 func main() { 35 if len(cacheDir) == 0 { 36 fmt.Print("cached dir must be set") 37 flag.Usage() 38 os.Exit(1) 39 } 40 41 writer := zerolog.NewConsoleWriter() 42 writer.TimeFormat = time.RFC3339 43 writer.FormatMessage = func(i interface{}) string { 44 return fmt.Sprintf("\033[1m%v\033[0m", i) 45 } 46 writer.FormatTimestamp = func(i interface{}) string { 47 if i == nil { 48 return "" 49 } 50 return fmt.Sprintf("\033[2m%v\033[0m", i) 51 } 52 writer.FormatFieldName = func(i interface{}) string { 53 return fmt.Sprintf("\033[35m%s\033[0m", i) 54 } 55 writer.FormatFieldValue = func(i interface{}) string { 56 return fmt.Sprintf("[%v]", i) 57 } 58 writer.FormatErrFieldName = func(i interface{}) string { 59 return fmt.Sprintf("\033[31m%s\033[0m", i) 60 } 61 writer.FormatErrFieldValue = 62 func(i interface{}) string { 63 return fmt.Sprintf("\033[31m[%v]\033[0m", i) 64 } 65 log := zerolog.New(writer).Level(zerolog.DebugLevel) 66 67 errCh := make(chan error) 68 69 log.Info().Str("listen", listen).Msg("start listening") 70 71 r, err := goproxy.NewRouter() 72 if err != nil { 73 log.Fatal().Err(err) 74 } 75 76 legacy, err := vcs.NewPlugin(cacheDir) 77 if err != nil { 78 log.Fatal().Err(err).Msg("exiting") 79 } 80 if err := r.AddRoute("", legacy); err != nil { 81 log.Fatal().Err(err).Msg("exiting") 82 } 83 84 if len(gitlabAPIURL) > 0 { 85 gl := gitlab.NewPlugin(gitlab2.NewAPIAccess(nil, gitlabAPIURL), true) 86 if err := r.AddRoute("gitlab", gl); err != nil { 87 log.Fatal().Err(err).Msg("exiting") 88 } 89 } 90 91 m := goproxy.NewMiddleware(r, "", &log) 92 93 server := http.Server{ 94 Addr: listen, 95 Handler: m, 96 } 97 98 go func() { 99 err := server.ListenAndServe() 100 if err != nil { 101 errCh <- err 102 } 103 }() 104 105 signCh := make(chan os.Signal) 106 signal.Notify(signCh, os.Interrupt, syscall.SIGTERM) 107 108 select { 109 case err := <-errCh: 110 log.Fatal().Err(err).Msg("exiting") 111 case sign := <-signCh: 112 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) 113 defer cancel() 114 _ = server.Shutdown(ctx) 115 log.Info().Str("signal", sign.String()).Msg("server stopped on signal") 116 } 117 }