MCPcopy
hub / github.com/elastic/go-elasticsearch / main

Function main

_examples/interceptor/cmd/context_auth/main.go:37–87  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

35)
36
37func main() {
38 // Start a fake Elasticsearch server that logs incoming auth credentials
39 srv := fake.NewServer(
40 fake.WithLogFn(func(r *http.Request) {
41 username, password, _ := redact.BasicAuth(r)
42 slog.Info("server received request",
43 slog.String("method", r.Method),
44 slog.String("path", r.URL.Path),
45 slog.String("username", username),
46 slog.String("password", password),
47 )
48 }),
49 fake.WithStatusCode(http.StatusOK),
50 fake.WithResponseBody([]byte(`{"cluster_name":"example"}`)),
51 fake.WithHeaders(func(h http.Header) {
52 h.Set("X-Elastic-Product", "Elasticsearch")
53 h.Set("Content-Type", "application/json")
54 }),
55 )
56 defer srv.Close()
57
58 // Create an Elasticsearch client with default credentials and context auth interceptor
59 es, err := elasticsearch.New(
60 elasticsearch.WithAddresses(srv.URL()),
61 elasticsearch.WithBasicAuth("default_user", "default_password"),
62 elasticsearch.WithTransportOptions(elastictransport.WithInterceptors(
63 ContextAuthInterceptor(),
64 )),
65 )
66 if err != nil {
67 panic(err)
68 }
69
70 // Request without context override uses default credentials
71 fmt.Println(">>> Sending request with default credentials")
72 _, _ = es.Info()
73
74 // Request with context override uses the specified credentials
75 fmt.Println("\n>>> Sending request with context override (tenant_a)")
76 ctx := WithBasicAuth(context.Background(), "tenant_a", "tenant_a_secret")
77 _, _ = es.Info(es.Info.WithContext(ctx))
78
79 // Another request with different context credentials
80 fmt.Println("\n>>> Sending request with context override (tenant_b)")
81 ctx = WithBasicAuth(context.Background(), "tenant_b", "tenant_b_secret")
82 _, _ = es.Info(es.Info.WithContext(ctx))
83
84 // Request without context override still uses default credentials
85 fmt.Println("\n>>> Sending request with default credentials again")
86 _, _ = es.Info()
87}
88
89// basicAuthKey is the context key for storing basic auth credentials.
90type basicAuthKey struct{}

Callers

nothing calls this directly

Calls 14

URLMethod · 0.95
NewServerFunction · 0.92
WithLogFnFunction · 0.92
BasicAuthFunction · 0.92
WithStatusCodeFunction · 0.92
WithResponseBodyFunction · 0.92
WithHeadersFunction · 0.92
ContextAuthInterceptorFunction · 0.85
WithBasicAuthFunction · 0.70
CloseMethod · 0.65
InfoMethod · 0.45
StringMethod · 0.45

Tested by

no test coverage detected