forked from elastic/go-elasticsearch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
102 lines (80 loc) · 2.36 KB
/
main.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
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
98
99
100
101
102
// Licensed to Elasticsearch B.V. under one or more agreements.
// Elasticsearch B.V. licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
// +build ignore
// This examples demonstrates how extend the API of the client by embedding it inside a custom type.
package main
import (
"io"
"log"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"github.com/elastic/go-elasticsearch/v8"
"github.com/elastic/go-elasticsearch/v8/esapi"
"github.com/elastic/go-elasticsearch/v8/estransport"
)
const port = "9209"
// ExtendedClient allows to call regular and custom APIs.
//
type ExtendedClient struct {
*elasticsearch.Client
Custom *ExtendedAPI
}
// ExtendedAPI contains custom APIs.
//
type ExtendedAPI struct {
*elasticsearch.Client
}
// Example calls a custom REST API, "/_cat/example".
//
func (c *ExtendedAPI) Example() (*esapi.Response, error) {
req, _ := http.NewRequest("GET", "/_cat/example", nil) // errcheck exclude
res, err := c.Perform(req)
if err != nil {
return nil, err
}
return &esapi.Response{StatusCode: res.StatusCode, Body: res.Body, Header: res.Header}, nil
}
func main() {
log.SetFlags(0)
started := make(chan bool)
// --> Start the proxy server
//
go startServer(started)
esclient, err := elasticsearch.NewClient(elasticsearch.Config{
Addresses: []string{"http://localhost:" + port},
Logger: &estransport.ColorLogger{Output: os.Stdout, EnableRequestBody: true, EnableResponseBody: true},
})
if err != nil {
log.Fatalf("Error creating the client: %s", err)
}
es := ExtendedClient{Client: esclient, Custom: &ExtendedAPI{esclient}}
<-started
// --> Call a regular Elasticsearch API
//
es.Cat.Health()
// --> Call a custom API
//
es.Custom.Example()
}
func startServer(started chan<- bool) {
proxy := httputil.NewSingleHostReverseProxy(&url.URL{Scheme: "http", Host: "localhost:9200"})
// Respond with custom content on "GET /_cat/example", proxy to Elasticsearch for other requests
//
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" && r.URL.Path == "/_cat/example" {
io.WriteString(w, "Hello from Cat Example action")
return
}
proxy.ServeHTTP(w, r)
})
ln, err := net.Listen("tcp", "localhost:"+port)
if err != nil {
log.Fatalf("Unable to start server: %s", err)
}
go http.Serve(ln, nil)
started <- true
}