youtube-dl-service/backend/main.go

54 lines
1.1 KiB
Go

package main
import (
"fmt"
"log"
"net/http"
"time"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"github.com/kkdai/youtube/v2"
)
func init() {
log.SetPrefix("[youtube-dl-service] ")
}
func main() {
r := gin.Default()
r.Use(cors.New(cors.Config{
AllowOrigins: []string{"http://localhost:8080", "http://localhost:5000"},
AllowCredentials: true,
AllowHeaders: []string{"*"},
}))
r.Use(gin.CustomRecovery(func(c *gin.Context, recovered interface{}) {
if err, ok := recovered.(string); ok {
c.String(http.StatusInternalServerError, fmt.Sprintf("error: %s", err))
}
c.AbortWithStatus(http.StatusInternalServerError)
}))
r.GET("/get_video", func(c *gin.Context) {
id, err := youtube.ExtractVideoID(c.Query("url"))
if err != nil {
panic(err)
}
log.Printf("Extracted video ID: %s", id)
client := youtube.Client{}
video, err := client.GetVideo(id)
if err != nil {
panic(err)
}
c.JSON(200, gin.H{
"title": video.Title,
"duration": float64(video.Duration) / float64(time.Minute),
"thumbnails": video.Thumbnails[0],
})
})
r.Run()
}