|
| 1 | +// Copyright 2012-present Oliver Eilhard. All rights reserved. |
| 2 | +// Use of this source code is governed by a MIT-license. |
| 3 | +// See http://olivere.mit-license.org/license.txt for details. |
| 4 | + |
| 5 | +// Middleware via HTTP RoundTripper. |
| 6 | +// |
| 7 | +// Example |
| 8 | +// |
| 9 | +// middleware "http://127.0.0.1:9200/test-index?sniff=false&healthcheck=false" |
| 10 | +// |
| 11 | +package main |
| 12 | + |
| 13 | +import ( |
| 14 | + "flag" |
| 15 | + "fmt" |
| 16 | + "log" |
| 17 | + "net/http" |
| 18 | + "sync/atomic" |
| 19 | + |
| 20 | + "github.com/olivere/elastic/v7" |
| 21 | +) |
| 22 | + |
| 23 | +// CountingTransport will count requests. |
| 24 | +type CountingTransport struct { |
| 25 | + N int64 // number of requests passing this transport |
| 26 | + next http.RoundTripper // next round-tripper or http.DefaultTransport if nil |
| 27 | +} |
| 28 | + |
| 29 | +// RoundTrip implements a transport that will count requests. |
| 30 | +func (tr *CountingTransport) RoundTrip(r *http.Request) (*http.Response, error) { |
| 31 | + atomic.AddInt64(&tr.N, 1) |
| 32 | + if tr.next != nil { |
| 33 | + return tr.next.RoundTrip(r) |
| 34 | + } |
| 35 | + return http.DefaultTransport.RoundTrip(r) |
| 36 | +} |
| 37 | + |
| 38 | +func main() { |
| 39 | + var ( |
| 40 | + url = flag.String("url", "http://localhost:9200", "Elasticsearch URL") |
| 41 | + sniff = flag.Bool("sniff", true, "Enable or disable sniffing") |
| 42 | + ) |
| 43 | + flag.Parse() |
| 44 | + log.SetFlags(0) |
| 45 | + |
| 46 | + if *url == "" { |
| 47 | + *url = "http://127.0.0.1:9200" |
| 48 | + } |
| 49 | + |
| 50 | + tr := &CountingTransport{} |
| 51 | + |
| 52 | + // Create an Elasticsearch client |
| 53 | + client, err := elastic.NewClient( |
| 54 | + elastic.SetURL(*url), |
| 55 | + elastic.SetSniff(*sniff), |
| 56 | + elastic.SetHttpClient(&http.Client{ |
| 57 | + Transport: tr, |
| 58 | + }), |
| 59 | + ) |
| 60 | + if err != nil { |
| 61 | + log.Fatal(err) |
| 62 | + } |
| 63 | + |
| 64 | + // Get ES version |
| 65 | + indices, err := client.IndexNames() |
| 66 | + if err != nil { |
| 67 | + log.Fatal(err) |
| 68 | + } |
| 69 | + for _, index := range indices { |
| 70 | + fmt.Println(index) |
| 71 | + } |
| 72 | + |
| 73 | + // Just a status message |
| 74 | + fmt.Printf("%d requests executed.\n", tr.N) |
| 75 | +} |
0 commit comments