-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtiktok.go
78 lines (67 loc) · 1.91 KB
/
tiktok.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
package tiktok_api
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
)
const (
defaultHost = "https://www.tiktok.com"
reqEmbedUri = "/oembed"
)
// Response contains all the embedded object properties
type Response struct {
Version string `json:"version"`
Type string `json:"type"`
Title string `json:"title"`
AuthorUrl string `json:"author_url"`
AuthorName string `json:"author_name"`
Width string `json:"width"`
Height string `json:"height"`
Html string `json:"html"`
ThumbnailWidth uint64 `json:"thumbnail_width"`
ThumbnailHeight uint64 `json:"thumbnail_height"`
ThumbnailUrl string `json:"thumbnail_url"`
ProviderUrl string `json:"provider_url"`
ProviderName string `json:"provider_name"`
}
// TikTokService encapsulates settings for TikTok api calls
type TikTokService struct {
host string
}
// NewTikTokService creates TikTokService with default settings
func NewTikTokService() *TikTokService {
return &TikTokService{host: defaultHost}
}
// Embed allows you to get the embed code and additional information about the video associated with the webpage link provided
func (s *TikTokService) Embed(params map[string]string) (*Response, error) {
client := &http.Client{}
req, err := http.NewRequest(http.MethodGet, s.host+reqEmbedUri, nil)
if err != nil {
return nil, err
}
q := req.URL.Query()
for param, val := range params {
q.Add(param, val)
}
req.URL.RawQuery = q.Encode()
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
r := &Response{}
err = json.Unmarshal(respBody, r)
if err != nil {
return nil, err
}
if r.Version == "" && r.ProviderName == "" && r.Title == "" {
return nil, errors.New(fmt.Sprintf("Couldn't embed video source from uri: %s", q.Get("url")))
}
return r, nil
}