all repos — gopipe @ d9ab51a35a4242ee8f1f5c0760ced3905f84e872

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	// r.HandleFunc("/proxy/{videoId}", proxyHandler)
59	// r.HandleFunc("/clear", clearHandler)
60
61	// video handlers
62	r.HandleFunc("GET /watch", videoHandler)
63	r.HandleFunc("GET /{videoID}", videoHandler)
64	r.HandleFunc("GET /shorts/{videoID}", videoHandler)
65
66	// r.HandleFunc("GET /robots.txt", robotsHandler)
67
68	log.Println("Serving on port " + g.Port)
69	log.Fatal(http.ListenAndServe(":"+g.Port, serveMux))
70}