|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "log" |
| 6 | + "net/http" |
| 7 | + "os" |
| 8 | + "strings" |
| 9 | + |
| 10 | + "github.com/github/git-bundle-server/internal/core" |
| 11 | +) |
| 12 | + |
| 13 | +func parseRoute(path string) (string, string, string, error) { |
| 14 | + if len(path) == 0 { |
| 15 | + return "", "", "", fmt.Errorf("empty route") |
| 16 | + } |
| 17 | + |
| 18 | + if path[0] == '/' { |
| 19 | + path = path[1:] |
| 20 | + } |
| 21 | + |
| 22 | + slash1 := strings.Index(path, "/") |
| 23 | + if slash1 < 0 { |
| 24 | + return "", "", "", fmt.Errorf("route has owner, but no repo") |
| 25 | + } |
| 26 | + slash2 := strings.Index(path[slash1+1:], "/") |
| 27 | + if slash2 < 0 { |
| 28 | + // No trailing slash. |
| 29 | + return path[:slash1], path[slash1+1:], "", nil |
| 30 | + } |
| 31 | + slash2 += slash1 + 1 |
| 32 | + slash3 := strings.Index(path[slash2+1:], "/") |
| 33 | + if slash3 >= 0 { |
| 34 | + return "", "", "", fmt.Errorf("path has depth exceeding three") |
| 35 | + } |
| 36 | + |
| 37 | + return path[:slash1], path[slash1+1 : slash2], path[slash2+1:], nil |
| 38 | +} |
| 39 | + |
| 40 | +func serve(w http.ResponseWriter, r *http.Request) { |
| 41 | + path := r.URL.Path |
| 42 | + |
| 43 | + owner, repo, file, err := parseRoute(path) |
| 44 | + if err != nil { |
| 45 | + w.WriteHeader(http.StatusNotFound) |
| 46 | + fmt.Printf("Failed to parse route: %s\n", err) |
| 47 | + return |
| 48 | + } |
| 49 | + |
| 50 | + route := owner + "/" + repo |
| 51 | + |
| 52 | + repos, err := core.GetRepositories() |
| 53 | + if err != nil { |
| 54 | + w.WriteHeader(http.StatusInternalServerError) |
| 55 | + fmt.Printf("Failed to load routes\n") |
| 56 | + return |
| 57 | + } |
| 58 | + |
| 59 | + repository, contains := repos[route] |
| 60 | + if !contains { |
| 61 | + w.WriteHeader(http.StatusNotFound) |
| 62 | + fmt.Printf("Failed to get route out of repos\n") |
| 63 | + return |
| 64 | + } |
| 65 | + |
| 66 | + if file == "" { |
| 67 | + file = "bundle-list" |
| 68 | + } |
| 69 | + |
| 70 | + fileToServe := repository.WebDir + "/" + file |
| 71 | + data, err := os.ReadFile(fileToServe) |
| 72 | + if err != nil { |
| 73 | + w.WriteHeader(http.StatusNotFound) |
| 74 | + fmt.Printf("Failed to read file\n") |
| 75 | + return |
| 76 | + } |
| 77 | + |
| 78 | + fmt.Printf("Successfully serving content for %s/%s\n", route, file) |
| 79 | + w.Write(data) |
| 80 | +} |
| 81 | + |
| 82 | +func main() { |
| 83 | + // API routes |
| 84 | + http.HandleFunc("/", serve) |
| 85 | + |
| 86 | + port := ":8080" |
| 87 | + fmt.Println("Server is running on port" + port) |
| 88 | + |
| 89 | + // Start server on port specified above |
| 90 | + log.Fatal(http.ListenAndServe(port, nil)) |
| 91 | +} |
0 commit comments