Skip to content

Instantly share code, notes, and snippets.

@mottaquikarim
Created December 29, 2020 17:15
Show Gist options
  • Save mottaquikarim/dea851bbcc1767d8d100c4a6041a1847 to your computer and use it in GitHub Desktop.
Save mottaquikarim/dea851bbcc1767d8d100c4a6041a1847 to your computer and use it in GitHub Desktop.
func constructQuery(q string, size int) *strings.Reader {
// Build a query string from string passed to function
var query = `{"query": {`
// Concatenate query string with string passed to method call
query = query + q
// Use the strconv.Itoa() method to convert int to string
query = query + `}, "size": ` + strconv.Itoa(size) + `}`
fmt.Println("\nquery:", query)
// Check for JSON errors
isValid := json.Valid([]byte(query)) // returns bool
// Default query is "{}" if JSON is invalid
if isValid == false {
fmt.Println("constructQuery() ERROR: query string not valid:", query)
fmt.Println("Using default match_all query")
query = "{}"
} else {
fmt.Println("constructQuery() valid JSON:", isValid)
}
// Build a new string from JSON query
var b strings.Builder
b.WriteString(query)
// Instantiate a *strings.Reader object from string
read := strings.NewReader(b.String())
// Return a *strings.Reader object
return read
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment