all repos — gopipe @ 8c09f0e04a44434c6bd7e9a2e223155ad3b21670

Embed YouTube videos on Telegram, Discord and more!

src/app/main.go (view raw)

 1package app
 2
 3import (
 4	"log"
 5	"net/http"
 6	"os"
 7	"strings"
 8
 9	g "github.com/birabittoh/gopipe/src/globals"
10	"github.com/joho/godotenv"
11	"golang.org/x/time/rate"
12)
13
14func limit(limiter *rate.Limiter, next http.Handler) http.Handler {
15	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
16		if !limiter.Allow() {
17			status := http.StatusTooManyRequests
18			http.Error(w, http.StatusText(status), status)
19			return
20		}
21		next.ServeHTTP(w, r)
22	})
23}
24
25func getEnvDefault(key string, def string) string {
26	res := os.Getenv(key)
27	if res == "" {
28		return def
29	}
30	return res
31}
32
33func parseBool(s string) bool {
34	return strings.ToLower(s) == "true" || s == "1"
35}
36
37func Main() {
38	godotenv.Load()
39
40	g.Debug = parseBool(os.Getenv("APP_DEBUG"))
41	if g.Debug {
42		log.Println("Debug mode enabled.")
43	}
44
45	g.Port = getEnvDefault("APP_PORT", "3000")
46
47	r := http.NewServeMux()
48
49	var serveMux http.Handler
50	if g.Debug {
51		serveMux = r
52	} else {
53		limiter := rate.NewLimiter(rate.Limit(1), 3) // TODO: use env vars
54		serveMux = limit(limiter, r)
55	}
56
57	r.HandleFunc("GET /", indexHandler)
58
59	// video handlers
60	r.HandleFunc("GET /watch", videoHandler)
61	r.HandleFunc("GET /shorts/{videoID}", videoHandler)
62	r.HandleFunc("GET /{videoID}", videoHandler)
63	r.HandleFunc("GET /{videoID}/{formatID}", videoHandler)
64
65	// r.HandleFunc("GET /robots.txt", robotsHandler)
66
67	log.Println("Serving on port " + g.Port)
68	log.Fatal(http.ListenAndServe(":"+g.Port, serveMux))
69}