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 5package elastic 6 7import ( 8 "context" 9 "encoding/json" 10 "fmt" 11 "net/url" 12 13 "github.com/olivere/elastic/uritemplates" 14) 15 16// GetScriptService reads a stored script in Elasticsearch. 17// 18// See https://www.elastic.co/guide/en/elasticsearch/reference/6.7/modules-scripting.html 19// for details. 20type GetScriptService struct { 21 client *Client 22 pretty bool 23 id string 24} 25 26// NewGetScriptService creates a new GetScriptService. 27func NewGetScriptService(client *Client) *GetScriptService { 28 return &GetScriptService{ 29 client: client, 30 } 31} 32 33// Id is the script ID. 34func (s *GetScriptService) Id(id string) *GetScriptService { 35 s.id = id 36 return s 37} 38 39// Pretty indicates that the JSON response be indented and human readable. 40func (s *GetScriptService) Pretty(pretty bool) *GetScriptService { 41 s.pretty = pretty 42 return s 43} 44 45// buildURL builds the URL for the operation. 46func (s *GetScriptService) buildURL() (string, string, url.Values, error) { 47 var ( 48 err error 49 method = "GET" 50 path string 51 ) 52 53 path, err = uritemplates.Expand("/_scripts/{id}", map[string]string{ 54 "id": s.id, 55 }) 56 if err != nil { 57 return "", "", url.Values{}, err 58 } 59 60 // Add query string parameters 61 params := url.Values{} 62 if s.pretty { 63 params.Set("pretty", "true") 64 } 65 return method, path, params, nil 66} 67 68// Validate checks if the operation is valid. 69func (s *GetScriptService) Validate() error { 70 var invalid []string 71 if s.id == "" { 72 invalid = append(invalid, "Id") 73 } 74 if len(invalid) > 0 { 75 return fmt.Errorf("missing required fields: %v", invalid) 76 } 77 return nil 78} 79 80// Do executes the operation. 81func (s *GetScriptService) Do(ctx context.Context) (*GetScriptResponse, error) { 82 // Check pre-conditions 83 if err := s.Validate(); err != nil { 84 return nil, err 85 } 86 87 // Get URL for request 88 method, path, params, err := s.buildURL() 89 if err != nil { 90 return nil, err 91 } 92 93 // Get HTTP response 94 res, err := s.client.PerformRequest(ctx, PerformRequestOptions{ 95 Method: method, 96 Path: path, 97 Params: params, 98 }) 99 if err != nil { 100 return nil, err 101 } 102 103 // Return operation response 104 ret := new(GetScriptResponse) 105 if err := s.client.decoder.Decode(res.Body, ret); err != nil { 106 return nil, err 107 } 108 return ret, nil 109} 110 111// GetScriptResponse is the result of getting a stored script 112// from Elasticsearch. 113type GetScriptResponse struct { 114 Id string `json:"_id"` 115 Found bool `json:"found"` 116 Script json.RawMessage `json:"script"` 117} 118