linkinfo/linkinfo.go

65 lines
1.2 KiB
Go

package linkinfo
import (
"net/http"
"net/url"
"time"
)
type LinkHandler struct {
Hosts []string
Handler func(link string) (*LinkInfo, error)
}
type LinkInfoApi struct {
Client *http.Client
linkHandlers []*LinkHandler
}
type LinkInfo struct {
Title string `json:"title"`
Description string `json:"description"`
ContentType string `json:"type"`
ContentLength int64 `json:"contentLength"`
Duration string `json:"duration,omitempty"`
Redirects []string `json:"redirects,omitempty"`
}
func New() *LinkInfoApi {
api := &LinkInfoApi{
Client: &http.Client{
Timeout: 60 * time.Second,
},
}
api.registerDefaultHandlers()
return api
}
func (i *LinkInfoApi) registerDefaultHandlers() {
i.linkHandlers = []*LinkHandler{
{Hosts: youtubeHosts, Handler: i.YoutubeLinkHandler},
{Hosts: imgurHosts, Handler: i.ImgurLinkHandler},
{Hosts: twitterHosts, Handler: i.TwitterLinkHandler},
}
}
func (i *LinkInfoApi) Retrieve(link string) (*LinkInfo, error) {
u, err := url.Parse(link)
if err != nil {
return nil, err
}
for _, handler := range i.linkHandlers {
for _, host := range handler.Hosts {
if host == u.Hostname() {
return handler.Handler(link)
}
}
}
return i.DefaultLinkHandler(link)
}