gitshow.go (1949B)
1 package main 2 3 import ( 4 "bufio" 5 "github.com/gorilla/mux" 6 "log" 7 "net/http" 8 "os" 9 "time" 10 "github.com/go-git/go-git/v5" 11 "errors" 12 "path/filepath" 13 ) 14 15 func checkRepo(reponame string) (repo *git.Repository, err error) { 16 content, err := os.Open("project.list") 17 18 if err != nil { 19 return nil, errors.New("No project list") 20 } 21 defer content.Close() 22 23 scanner := bufio.NewScanner(content) 24 for scanner.Scan() { 25 if scanner.Text() == reponame { 26 return git.PlainOpen(filepath.Join("repositories", reponame)) 27 } 28 } 29 30 return nil, errors.New("Not authorized") 31 } 32 33 var reporouter *mux.Router 34 35 // Got from mux repository 36 func loggingMiddleware(next http.Handler) http.Handler { 37 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 38 log.Println(r.Method, r.RequestURI, r.Header["Hx-Request"]) 39 next.ServeHTTP(w, r) 40 }) 41 } 42 43 func main() { 44 log.SetPrefix("gitshow: ") 45 log.SetFlags(log.Ldate | log.Ltime) 46 47 logger := log.Default() 48 logger.Print("Starting...") 49 50 r := mux.NewRouter() 51 r.StrictSlash(true) 52 r.Use(loggingMiddleware) 53 54 r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("./static/")))) 55 56 reporouter = r.PathPrefix("/repos/{repository:[a-zA-Z-]+}").Subrouter() 57 58 reporouter.HandleFunc("/", getRepo).Methods("GET") 59 60 reporouter.HandleFunc("/log", getLog).Methods("GET") 61 62 reporouter.HandleFunc("/tree", getTree).Methods("GET") 63 reporouter.PathPrefix("/tree/{ref:[a-zA-Z0-9]+}/").HandlerFunc(getTree).Methods("GET").Name("tree") 64 65 reporouter.PathPrefix("/file/{ref:[a-z-A-Z0-9]+}/").HandlerFunc(getFile).Methods("GET").Name("file") 66 67 reporouter.HandleFunc("/commit/{hash:[a-f0-9]+}", getCommit).Methods("GET") 68 69 srv := &http.Server{ 70 Handler: r, 71 Addr: "127.0.0.1:8080", 72 // Good practice: enforce timeouts for servers you create! 73 WriteTimeout: 15 * time.Second, 74 ReadTimeout: 15 * time.Second, 75 } 76 77 logger.Print("Started.") 78 logger.Fatal(srv.ListenAndServe()) 79 }