aboutsummaryrefslogtreecommitdiffstats
path: root/useragents.go
blob: 0c51e6164b296c497fe9e647ff6ffbacb423e606 (plain) (blame)
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
package main

import (
	"bytes"
	"context"
	"crypto/tls"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"time"
)

const (
	UserAgentsURL = "https://useragents:443/api/v1/agent"
)

func UserAgentsGet(uaActionName, query string, appConfig *TomlConfig) string {
	var userAgentRequest UserAgentRequest

	var userAgentResponse UserAgentResponse

	_, ok := appConfig.UserAgentActions[uaActionName]
	if !ok {
		log.Println("UserAgentAction not found:", uaActionName)

		return fmt.Sprintf("useragents: %s: action not found", uaActionName)
	}

	userAgentRequest.Agent_Name = appConfig.UserAgentActions[uaActionName].Agent_Name
	userAgentRequest.Instructions = appConfig.UserAgentActions[uaActionName].Instructions
	userAgentRequest.Query = appConfig.UserAgentActions[uaActionName].Query

	if query != "" {
		userAgentRequest.Query = query
	}

	log.Println("UserAgentRequest:", appConfig.UserAgentActions[uaActionName])
	log.Println(userAgentRequest)

	jsonData, err := json.Marshal(userAgentRequest)
	if err != nil {
		log.Println(err)

		return fmt.Sprintf("useragents: %s: could not marshall json request", userAgentRequest.Agent_Name)
	}

	ctx, cancel := context.WithTimeout(context.Background(), time.Duration(appConfig.RequestTimeout)*time.Second)
	defer cancel()

	req, err := http.NewRequest(
		http.MethodPost,
		UserAgentsURL,
		bytes.NewBuffer(jsonData),
	)
	if err != nil {
		log.Println(err)

		return fmt.Sprintf("useragents: %s: could not create request", userAgentRequest.Agent_Name)
	}

	req = req.WithContext(ctx)

	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{
				InsecureSkipVerify: true,
			},
		},
	}

	response, err := client.Do(req)
	if err != nil {
		log.Println(err)

		return fmt.Sprintf("useragents: %s: could not send request", userAgentRequest.Agent_Name)
	}

	defer response.Body.Close()

	if err != nil {
		log.Println(err)

		return fmt.Sprintf("useragents: %s: could not read response", userAgentRequest.Agent_Name)
	}

	err = json.NewDecoder(response.Body).Decode(&userAgentResponse)
	if err != nil {
		log.Println(err)

		return fmt.Sprintf("useragents: %s: could not unmarshall json response", userAgentRequest.Agent_Name)
	}

	return userAgentResponse.Response
}