-
Notifications
You must be signed in to change notification settings - Fork 0
/
channels.go
101 lines (85 loc) · 1.88 KB
/
channels.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package main
import (
"bytes"
_ "embed"
"encoding/json"
"fmt"
"net/http"
"net/url"
"path/filepath"
"github.com/labstack/echo/v4"
)
type Channel struct {
Name string
Slug string
URL *url.URL
}
func (c *Channel) UnmarshalJSON(data []byte) error {
raw := struct {
Name string
Slug string
URL string
}{}
if err := json.Unmarshal(data, &raw); err != nil {
return err
}
u, err := url.Parse(raw.URL)
if err != nil {
return err
}
*c = Channel{
Name: raw.Name,
Slug: raw.Slug,
URL: u,
}
return nil
}
func (c *Channel) SegmentURL(rendition string, segment string) string {
return "https://" + c.URL.Host + filepath.Join(c.PlaylistBasePath(), rendition, segment)
}
func (c *Channel) RenditionURL(rendition string) string {
return "https://" + c.URL.Host + filepath.Join(c.PlaylistBasePath(), rendition, "playlist.m3u8")
}
func (c *Channel) PlaylistBasePath() string {
return filepath.Dir(c.URL.Path)
}
type Channels []*Channel
func (cs Channels) BySlug(slug string) (*Channel, bool) {
for _, c := range cs {
if c.Slug == slug {
return c, true
}
}
return nil, false
}
var (
//go:embed channels.json
channelsData []byte
)
func LoadChannels() (Channels, error) {
var channels Channels
err := json.NewDecoder(bytes.NewReader(channelsData)).Decode(&channels)
return channels, err
}
const (
channelContextKey = "channel"
)
func ChannelFromContext(c echo.Context) (*Channel, error) {
channel, ok := c.Get(channelContextKey).(*Channel)
if ok {
return channel, nil
}
return nil, fmt.Errorf("channel not found")
}
func LoadChannelBySlug(channels Channels) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
channel, ok := channels.BySlug(c.Param("channelSlug"))
if !ok {
return c.String(http.StatusNotFound, "not found")
}
c.Set(channelContextKey, channel)
return next(c)
}
}
}