70 lines
1.3 KiB
Go
70 lines
1.3 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"os/signal"
|
|
"syscall"
|
|
"time"
|
|
|
|
"github.com/julienschmidt/httprouter"
|
|
)
|
|
|
|
func newRouter() *httprouter.Router {
|
|
apiKey := os.Getenv("YOUTUBE_API_KEY")
|
|
channelID := os.Getenv("YOUTUBE_CHANNEL_ID")
|
|
|
|
if apiKey == "" {
|
|
log.Fatalln("YOUTUBE_API_KEY is required")
|
|
}
|
|
|
|
if channelID == "" {
|
|
log.Fatalln("YOUTUBE_CHANNEL_ID is required")
|
|
}
|
|
|
|
router := httprouter.New()
|
|
router.GET("/stats", getChannelStats(apiKey, channelID))
|
|
return router
|
|
}
|
|
|
|
func main() {
|
|
srv := &http.Server{
|
|
Addr: ":8080",
|
|
Handler: newRouter(),
|
|
}
|
|
|
|
idleConnsClosed := make(chan struct{})
|
|
go func() {
|
|
|
|
sigint := make(chan os.Signal, 1)
|
|
signal.Notify(sigint, os.Interrupt)
|
|
signal.Notify(sigint, syscall.SIGTERM)
|
|
<-sigint
|
|
|
|
log.Println("Shutting down server...")
|
|
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
|
defer cancel()
|
|
|
|
if err := srv.Shutdown(ctx); err != nil {
|
|
log.Printf("error shutting down server: %v", err)
|
|
}
|
|
|
|
log.Println("Server shut down")
|
|
close(idleConnsClosed)
|
|
|
|
}()
|
|
|
|
log.Println("Server is running at :8080")
|
|
if err := srv.ListenAndServe(); err != nil {
|
|
if !errors.Is(err, http.ErrServerClosed) {
|
|
log.Fatalf("fatal http server error: %v", err)
|
|
}
|
|
}
|
|
|
|
<-idleConnsClosed
|
|
log.Println("Exiting...")
|
|
}
|