vue-movie/server/main.go
2021-03-11 18:53:20 +08:00

116 lines
2.1 KiB
Go

package main
import (
"bytes"
"fmt"
"io/fs"
"log"
"net/http"
"os/exec"
"path/filepath"
"strconv"
"strings"
"github.com/gin-gonic/gin"
)
// Movie 电影结构
type Movie struct {
Name string `json:"filename"`
Image string `json:"image"`
}
var movies []Movie
func initMovie() {
var movieDict map[string]string = make(map[string]string)
matches, err := filepath.Glob("movie/*")
if err != nil {
log.Println(err)
}
for _, filename := range matches {
base := filepath.Base(filename)
ext := filepath.Ext(base)
base = base[:strings.IndexByte(base, '.')]
if _, ok := movieDict[base]; ok {
delete(movieDict, base)
} else {
movieDict[base] = filename
}
log.Println(base, ext)
}
for key, filename := range movieDict {
width := 160
height := 120
log.Println(filename)
cmd := exec.Command("ffmpeg", "-i", filename, "-vframes", "1", "-s", fmt.Sprintf("%dx%d", width, height), "movie/"+key+".webp")
var buffer bytes.Buffer
cmd.Stdout = &buffer
if cmd.Run() != nil {
panic("could not generate frame")
}
}
filepath.Walk("./movie", func(path string, info fs.FileInfo, err error) error {
if !info.IsDir() && filepath.Ext(info.Name()) != "webp" {
base := info.Name()
log.Println(path, info.Name())
movies = append(movies, Movie{
Name: info.Name(),
Image: base[:strings.IndexByte(base, '.')] + ".webp",
})
}
return nil
})
log.Printf("%##v", movies)
}
func main() {
initMovie()
eg := gin.Default()
eg.Use(Cors())
eg.Static("/res", "movie/")
movie := eg.Group("movie")
movie.GET("/", func(c *gin.Context) {
var page int = 0
spage := c.Query("page")
if spage != "" {
p, err := strconv.Atoi(spage)
if err != nil {
log.Println(err)
}
page = p - 1
}
var limit int = 10
slimit := c.Query("limit")
if slimit != "" {
l, err := strconv.Atoi(slimit)
if err != nil {
log.Println(err)
}
limit = l
}
start := page * limit
log.Println(limit)
c.JSON(0, gin.H{
"code": http.StatusOK,
"message": "",
"data": movies[start : start+limit],
})
})
eg.Run(":4444")
}