|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "errors" |
| 5 | + "fmt" |
| 6 | + "log" |
| 7 | + "net/http" |
| 8 | + "path/filepath" |
| 9 | + |
| 10 | + "github.com/go-git/go-billy/v5/osfs" |
| 11 | + githttp "github.com/go-git/go-git/v6/plumbing/http" |
| 12 | + "github.com/go-git/go-git/v6/plumbing/transport" |
| 13 | + "github.com/spf13/cobra" |
| 14 | +) |
| 15 | + |
| 16 | +var port int |
| 17 | + |
| 18 | +func init() { |
| 19 | + rootCmd.Flags().IntVarP(&port, "port", "p", 8080, "Port to run the HTTP server on") |
| 20 | +} |
| 21 | + |
| 22 | +var rootCmd = &cobra.Command{ |
| 23 | + Use: "gogit-http-server [options] <directory>", |
| 24 | + Short: "Run a Go Git HTTP server", |
| 25 | + Args: cobra.ExactArgs(1), |
| 26 | + RunE: func(cmd *cobra.Command, args []string) error { |
| 27 | + directory := args[0] |
| 28 | + addr := fmt.Sprintf(":%d", port) |
| 29 | + abs, err := filepath.Abs(directory) |
| 30 | + if err != nil { |
| 31 | + return fmt.Errorf("failed to get absolute path: %w", err) |
| 32 | + } |
| 33 | + |
| 34 | + log.Printf("Using absolute path: %q", abs) |
| 35 | + loader := transport.NewFilesystemLoader(osfs.New(abs, osfs.WithBoundOS()), false) |
| 36 | + handler := &githttp.Handler{ |
| 37 | + Loader: loader, |
| 38 | + ErrorLog: log.Default(), |
| 39 | + } |
| 40 | + log.Printf("Starting server on %q for directory %q", addr, directory) |
| 41 | + if err := http.ListenAndServe(addr, handler); !errors.Is(err, http.ErrServerClosed) { |
| 42 | + return err |
| 43 | + } |
| 44 | + return nil |
| 45 | + }, |
| 46 | +} |
| 47 | + |
| 48 | +func main() { |
| 49 | + if err := rootCmd.Execute(); err != nil { |
| 50 | + log.Fatal(err) |
| 51 | + } |
| 52 | +} |
0 commit comments