aboutsummaryrefslogtreecommitdiff
path: root/internal/ogtags/cache.go
blob: b3e35e4fb546e9b03306e38ccea2fefae30c4b9f (plain)
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
package ogtags

import (
	"errors"
	"log/slog"
	"net/url"
	"syscall"
)

// GetOGTags is the main function that retrieves Open Graph tags for a URL
func (c *OGTagCache) GetOGTags(url *url.URL) (map[string]string, error) {
	if url == nil {
		return nil, errors.New("nil URL provided, cannot fetch OG tags")
	}
	urlStr := c.getTarget(url)
	// Check cache first
	if cachedTags := c.checkCache(urlStr); cachedTags != nil {
		return cachedTags, nil
	}

	// Fetch HTML content
	doc, err := c.fetchHTMLDocument(urlStr)
	if errors.Is(err, syscall.ECONNREFUSED) {
		slog.Debug("Connection refused, returning empty tags")
		return nil, nil
	} else if errors.Is(err, ErrOgHandled) {
		// Error was handled in fetchHTMLDocument, return empty tags
		return nil, nil
	}
	if err != nil {
		return nil, err
	}

	// Extract OG tags
	ogTags := c.extractOGTags(doc)

	// Store in cache
	c.cache.Set(urlStr, ogTags, c.ogTimeToLive)

	return ogTags, nil
}

// checkCache checks if we have the tags cached and returns them if so
func (c *OGTagCache) checkCache(urlStr string) map[string]string {
	if cachedTags, ok := c.cache.Get(urlStr); ok {
		slog.Debug("cache hit", "tags", cachedTags)
		return cachedTags
	}
	slog.Debug("cache miss", "url", urlStr)
	return nil
}