-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
74 lines (60 loc) · 1.51 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package main
import (
"fmt"
"log"
"os"
"sort"
"strings"
"time"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
)
func main() {
images := loadImages()
boundary := "--boundary"
router := gin.Default()
router.Use(cors.New(cors.Config{
AllowOrigins: []string{"*"},
AllowMethods: []string{"GET"},
AllowHeaders: []string{"Origin", "Content-Type"},
ExposeHeaders: []string{"Content-Length"},
}))
router.GET("/mjpeg", func(c *gin.Context) {
c.Header("content-type", "multipart/x-mixed-replace; boundary="+boundary)
imageIdx := 0
for {
c.Writer.Write([]byte(fmt.Sprintf("\r\n--%s\r\n", boundary)))
c.Writer.Write([]byte("Content-Type: image/jpeg\r\n"))
c.Writer.Write([]byte(fmt.Sprintf("Content-Length: %d\r\n\r\n", len(images[imageIdx]))))
c.Writer.Write(images[imageIdx])
c.Writer.Write([]byte(boundary))
c.Writer.Flush()
imageIdx++
imageIdx = imageIdx % len(images)
time.Sleep(30 * time.Millisecond)
}
})
router.Run(":3333")
}
func loadImages() (output [][]byte) {
baseDir := "images"
files, err := os.ReadDir(baseDir)
if err != nil {
log.Fatal(err)
}
imageFileNames := []string{}
for _, file := range files {
if !file.IsDir() && strings.Contains(file.Name(), ".jpg") {
imageFileNames = append(imageFileNames, file.Name())
}
}
sort.Strings(imageFileNames)
for _, fileName := range imageFileNames {
bytes, err := os.ReadFile(fmt.Sprintf("%s/%s", baseDir, fileName))
if err != nil {
log.Fatal(err)
}
output = append(output, bytes)
}
return
}