Splunk Part I

Recently I found a Go repo for a Splunk API Client that I really like. I decided to add some functionality. I was looking for something robust that could be fleshed out immediately.
Find the repo here.
To follow along import the repo and add the following code to the files main.go & splunk.go

Step 1: Add this code to splunk.go

func (conn SplunkConnection) CreateSearch() error {
    data := make(url.Values)
    data.Add("search", "search *")
    response, err := conn.httpPost(fmt.Sprintf("%s/services/search/jobs", conn.BaseURL), &data)

    if err != nil {
        return err
    }
    fmt.Println(response)
    return err
}


Step 2: Add this code to the example usage e.g. main.go

err = conn.CreateSearch()
    if err != nil {
            fmt.Println("Couldn't create search: %s", err)
    }


Response

<?xml version="1.0" encoding="UTF-8"?>
<response>
  <sid>1525219427.152</sid>
</response>


Next Step: Retrieving the unique search id


Decoding the XML response into a struct, we need to store this search id to retrieve its data and to poll its status.

Step 1:


Add this code to splunk.go

func (conn SplunkConnection) CreateSearch() (SearchResponse, error) {
    data := make(url.Values)
    data.Add("search", "search *")
    response, err := conn.httpPost(fmt.Sprintf("%s/services/search/jobs", conn.BaseURL), &data)
    if err != nil {
        return SearchResponse{}, err
    }
    bytes := []byte(response)
    var sid SearchResponse
    unmarshall_error := xml.Unmarshal(bytes, &sid)
    return sid, unmarshall_error
}


And this code.

type SearchResponse struct {
    XMLName xml.Name `xml:"response"`
    Sid string `xml:"sid"`
}


Step 2:


Add this code to main.go

package main

import (
    "fmt"
    "github.com/drewrm/splunk"
)

func main() {
    conn := splunk.SplunkConnection {
            Username: "username",
            Password: "password",
            BaseURL: "https://ip:8089",
    }

    key, err:= conn.Login()

    if err != nil {
            fmt.Println("Couldn't login to splunk: %s", err)
    }

    fmt.Println("Session key: ", key.Value)

   
sid, err := conn.CreateSearch()
    if err != nil {
            fmt.Println("Couldn't create search: %s", err)
    }
    fmt.Println("sid is = " + sid.Sid)


Which gives us this below.

sid is = 1525223806.160


or unique id for search is = 1525223806.160

Written on May 1, 2018