-
Notifications
You must be signed in to change notification settings - Fork 0
/
render.go
180 lines (150 loc) · 3.4 KB
/
render.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
package sgo
import (
"bytes"
"compress/gzip"
"context"
"crypto/sha1"
"fmt"
"github.com/chromedp/chromedp"
"github.com/hashicorp/golang-lru"
"io"
"io/ioutil"
"log"
"net/http"
"sync"
"time"
)
type Config struct {
CacheSize int
WaitTime time.Duration
CacheTime int64
Compress string
}
type render struct {
Config
cache *lru.Cache
cacheTime int64
mutex sync.Mutex
cacheMutex sync.Mutex
}
type Response struct {
Status int
Content string
ContentType string
}
type cachedResponse struct {
Status int
CompressedContent []byte
ContentType string
CacheTime int64
}
func (s *render) urlHash(url string) string {
h := sha1.New()
h.Write([]byte(url))
return fmt.Sprintf("%x\n", h.Sum(nil))
}
func (s *render) getFromCache(url string) (file *Response, ok bool) {
s.cacheMutex.Lock()
defer s.cacheMutex.Unlock()
urlHash := s.urlHash(url)
if cacheResult, ok := s.cache.Get(urlHash); ok {
cachedResponse := cacheResult.(cachedResponse)
//cache expired
if s.cacheTime > 0 && (cachedResponse.CacheTime+s.cacheTime) < time.Now().Unix() {
s.cache.Remove(urlHash)
return nil, false
}
in := *bytes.NewBuffer(cachedResponse.CompressedContent)
var out bytes.Buffer
r, _ := gzip.NewReader(&in)
_, _ = io.Copy(&out, r)
return &Response{
Status: cachedResponse.Status,
Content: out.String(),
ContentType: cachedResponse.ContentType,
}, true
}
return nil, false
}
func (s *render) setCache(url string, response *Response) {
s.cacheMutex.Lock()
defer s.cacheMutex.Unlock()
urlHash := s.urlHash(url)
var in bytes.Buffer
b := []byte(response.Content)
w := gzip.NewWriter(&in)
_, _ = w.Write(b)
_ = w.Close()
s.cache.Add(urlHash, cachedResponse{
Status: response.Status,
CompressedContent: in.Bytes(),
ContentType: response.ContentType,
CacheTime: time.Now().Unix(),
})
}
func (s *render) GetSSR(url string) (response *Response, hitCache bool, err error) {
response = nil
hitCache = false
if file, ok := s.getFromCache(url); ok {
return file, true, nil
}
// create context
ctx, cancel := chromedp.NewContext(context.Background())
defer cancel()
requestUrl := url
startTime := time.Now()
resp, err := http.Head(requestUrl)
if err != nil {
return
}
defer resp.Body.Close()
duration := time.Now().Sub(startTime)
contentType := resp.Header.Get("Content-Type")
// run task list
strChn := make(chan string)
//only render `text/html`
if contentType == `text/html` {
go func() {
var res string
err := chromedp.Run(ctx,
chromedp.Navigate(requestUrl),
chromedp.Sleep(duration + s.WaitTime*time.Second),
chromedp.OuterHTML(`html`, &res, chromedp.NodeVisible, chromedp.ByQuery),
)
if err != nil {
log.Fatal(err)
}
strChn <- res
close(strChn)
}()
} else {
go func() {
resp, err := http.Get(requestUrl)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
strChn <- string(body)
close(strChn)
}()
}
response = &Response{
Status: resp.StatusCode,
Content: <-strChn,
ContentType: contentType,
}
s.setCache(url, response)
return response, false, nil
}
func NewRender(config Config) *render {
lruCache, _ := lru.New(config.CacheSize)
return &render{
Config: config,
cache: lruCache,
cacheTime: config.CacheTime,
}
}