Skip to content

Instantly share code, notes, and snippets.

@danzek danzek/getESindices.go
Last active Jan 2, 2018

Embed
What would you like to do?
Print Elasticsearch indices
// Get list of indices from Elasticsearch.
// Yes, I know this boils down to `curl http://localhost:9200/_cat/indices` and shows less information.
// I did this as a personal exercise while learning Go.
/*
Public Domain. Use this however you wish!
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package main
import (
"bufio"
"fmt"
"io/ioutil"
"net/http"
"os"
"strings"
)
func main() {
// assume localhost but allow IP address or hostname parameter
// for now, port 9200 is not optional
host := "localhost"
if len(os.Args) > 1 {
host = os.Args[1]
}
url := fmt.Sprintf("http://%s:9200/_cat/indices", host)
fmt.Println("Searching for Elasticsearch indices....")
// get indices response
resp, err := http.Get(url)
if err != nil {
fmt.Fprintf(os.Stderr, "\nUnable to fetch indices: %v", err)
}
defer resp.Body.Close()
// check status code from response is 200 (http.StatusOK)
if resp.StatusCode == http.StatusOK {
// get data as bytes then convert to string
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Fprintf(os.Stderr, "\nUnable to get response body as bytes: %v", err)
}
bodyString := string(bodyBytes)
// iterate over response line by line and print indices found to stdout
scanner := bufio.NewScanner(strings.NewReader(bodyString))
for scanner.Scan() {
line := strings.Split(scanner.Text(), " ")
index := strings.TrimSpace(line[2])
fmt.Printf("\nIndex found: %s", index)
}
} else {
fmt.Fprintf(os.Stderr, "\nStatus code %v returned.", resp.StatusCode)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.