This repository was archived by the owner on Jun 15, 2021. It is now read-only.
forked from drewrm/splunk-golang
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsplunk.go
69 lines (54 loc) · 1.74 KB
/
splunk.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
package splunk
import (
"encoding/json"
"errors"
"fmt"
"net/url"
"os"
)
type SplunkConnection struct {
Username, Password, BaseURL string
sessionKey SessionKey
}
// SessionKey represents the JSON object returned from the Splunk authentication REST call
type SessionKey struct {
Value string `json:"sessionKey,omitempty"`
}
// Login connects to the Splunk server and retrieves a session key
func (conn *SplunkConnection) Login() (SessionKey, error) {
data := make(url.Values)
data.Add("username", conn.Username)
data.Add("password", conn.Password)
data.Add("output_mode", "json")
response, err := conn.httpPost(fmt.Sprintf("%s/services/auth/login", conn.BaseURL), &data)
if err != nil {
return SessionKey{}, err
}
bytes := []byte(response)
var key SessionKey
unmarshall_error := json.Unmarshal(bytes, &key)
if key.Value == "" {
return SessionKey{}, errors.New(response)
}
conn.sessionKey.Value = key.Value
return conn.sessionKey, unmarshall_error
}
func CreateConnectionFromEnvironment() (*SplunkConnection, error) {
var splunkUsername string
var splunkPassword string
var splunkUrl string
if splunkUsername = os.Getenv("SPLUNK_USERNAME"); splunkUsername == "" {
return nil, fmt.Errorf("Invalid value for environment variable SPLUNK_USERNAME: %v", splunkUsername)
}
if splunkPassword = os.Getenv("SPLUNK_PASSWORD"); splunkPassword == "" {
return nil, fmt.Errorf("Invalid value for environment variable SPLUNK_PASSWORD: %v", splunkPassword)
}
if splunkUrl = os.Getenv("SPLUNK_URL"); splunkUrl == "" {
return nil, fmt.Errorf("Invalid value for environment variable SPLUNK_URL: %v", splunkUrl)
}
return &SplunkConnection{
Username: splunkUsername,
Password: splunkPassword,
BaseURL: splunkUrl,
}, nil
}