~poptart/x

ref: 197bcbf285bb2a64f7e524b8ea051918f0253ec8 x/ua/ua.go -rw-r--r-- 1.5 KiB View raw
197bcbf2 — terrorbyte Added UA basics. 4 months ago
                                                                                
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 useragent

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"regexp"
	"strconv"
	"time"
)

var DEFAULT_INTERVAL = int(time.Hour * 24 * 30)
var UA_URL = "https://raw.githubusercontent.com/chromium/chromium/master/content/public/common/user_agent.h"
var REG1 = `Mozilla\/5.0 \(Windows[^"]*`
var REG2 = `like Gecko\) Chrome[^"]*`

type UserAgentCache struct {
	LastUpdate string
	Interval   int
	UserAgent  string
}

func GetCurrentUA() (string, error) {
	re1 := regexp.MustCompile(REG1)
	re2 := regexp.MustCompile(REG2)
	resp, err := http.Get(UA_URL)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	m1 := re1.Find(body)
	m2 := re2.Find(body)
	return fmt.Sprintf("%s%s", string(m1), string(m2)), nil
}

func SaveUACache(file string) error {
	t := time.Now().Unix()
	ua, err := GetCurrentUA()
	if err != nil {
		return err
	}
	uac := UserAgentCache{
		Interval:   DEFAULT_INTERVAL,
		LastUpdate: strconv.FormatInt(t, 10),
		UserAgent:  ua,
	}
	uaf, err := json.Marshal(uac)
	if err != nil {
		return err
	}
	err = ioutil.WriteFile(file, []byte(uaf), 0644)
	if err != nil {
		return err
	}
	return nil
}

//func GetUA() (string, error) {
//
//}

func GetUACache(file string) (UserAgentCache, error) {
	var uac UserAgentCache
	uaf, err := ioutil.ReadFile(file)
	if err != nil {
		return UserAgentCache{}, err
	}
	err = json.Unmarshal(uaf, &uac)
	if err != nil {
		return UserAgentCache{}, err
	}
	return uac, nil
}