query

package module
v1.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 16, 2021 License: MIT Imports: 7 Imported by: 11

README

query-go

GoDoc Build Status codecov Go Report Card LICENSE

This is a Go package to extract value by a query string like key[0].key["key"]. See usage and example in GoDoc.

Basic Usage

ParseString parses a query string and returns the query which extracts the value.

q, err := query.ParseString(`key[0].key["key"]`)
v, err := q.Extract(target)

Query Syntax

The query syntax understood by this package when parsing is as follows.

.key        extracts by a key of map or field name of struct ("." can be omitted if the head of query)
[0]         extracts by a index of array or slice
["key"]     same as the ".key"

Documentation

Overview

Package query provides to extract the element from a value.

ParseString parses a query string and returns the query which extracts the value.

q, err := query.ParseString(`key[0].key["key"]`)
v, err := q.Extract(target)

Query Syntax

The query syntax understood by this package when parsing is as follows.

.key        extracts by a key of map or field name of struct ("." can be omitted if the head of query)
[0]         extracts by a index of array or slice
["key"]     same as the ".key"

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Extractor

type Extractor interface {
	Extract(v reflect.Value) (reflect.Value, bool)
	String() string
}

An Extractor interface is used by a query to extract the element from a value.

type Index

type Index struct {
	// contains filtered or unexported fields
}

Index represents an extractor to access the value by index.

func (*Index) Extract

func (e *Index) Extract(v reflect.Value) (reflect.Value, bool)

Extract extracts the value from v by index. It reports whether the index is found and returns the found value.

If v implements the IndexExtractor interface, this method extracts by calling v.ExtractByIndex.

func (*Index) String

func (e *Index) String() string

String returns e as string.

type IndexExtractor

type IndexExtractor interface {
	ExtractByIndex(index int) (interface{}, bool)
}

IndexExtractor is the interface that wraps the ExtractByIndex method.

ExtractByIndex extracts the value by index. It reports whether the index is found and returns the found value.

type Key

type Key struct {
	// contains filtered or unexported fields
}

Key represents an extractor to access the value by key.

func (*Key) Extract

func (e *Key) Extract(v reflect.Value) (reflect.Value, bool)

Extract extracts the value from v by key. It reports whether the key is found and returns the found value.

If v implements the KeyExtractor interface, this method extracts by calling v.ExtractByKey.

func (*Key) String

func (e *Key) String() string

String returns e as string.

type KeyExtractor

type KeyExtractor interface {
	ExtractByKey(key string) (interface{}, bool)
}

KeyExtractor is the interface that wraps the ExtractByKey method.

ExtractByKey extracts the value by key. It reports whether the key is found and returns the found value.

Example
package main

import (
	"fmt"

	"github.com/zoncoen/query-go"
)

type orderedMap struct {
	elems []*elem
}

type elem struct {
	k, v interface{}
}

func (m *orderedMap) ExtractByKey(key string) (interface{}, bool) {
	for _, e := range m.elems {
		if k, ok := e.k.(string); ok {
			if k == key {
				return e.v, true
			}
		}
	}
	return nil, false
}

func main() {
	q := query.New().Key("key")
	v, _ := q.Extract(&orderedMap{
		elems: []*elem{{k: "key", v: "value"}},
	})
	fmt.Println(v)
}
Output:

value

type Option

type Option func(*Query)

Option represents an option for Query.

func CustomStructFieldNameGetter

func CustomStructFieldNameGetter(f func(f reflect.StructField) string) Option

CustomStructFieldNameGetter returns the Option to set f as custom function which gets struct field name. f is called by Key.Extract to get struct field name, if the target value is a struct.

Example
package main

import (
	"fmt"
	"reflect"
	"strings"

	"github.com/zoncoen/query-go"
)

// Person represents a person.
type Person struct {
	Name string `json:"name,omitempty"`
}

// getFieldNameByJSONTag returns the JSON field tag as field name if exists.
func getFieldNameByJSONTag(field reflect.StructField) string {
	tag, ok := field.Tag.Lookup("json")
	if ok {
		strs := strings.Split(tag, ",")
		return strs[0]
	}
	return field.Name
}

func main() {
	person := Person{
		Name: "Alice",
	}

	q := query.New(
		query.CustomStructFieldNameGetter(getFieldNameByJSONTag),
	).Key("name")
	name, _ := q.Extract(person)
	fmt.Println(name)
}
Output:

Alice

type Query

type Query struct {
	// contains filtered or unexported fields
}

Query represents a query to extract the element from a value.

func New

func New(opts ...Option) *Query

New returns a new query.

func Parse

func Parse(r io.Reader, opts ...Option) (*Query, error)

Parse parses a query string via r and returns the corresponding Query.

func ParseString

func ParseString(s string, opts ...Option) (*Query, error)

ParseString parses a query string s and returns the corresponding Query.

Example
package main

import (
	"fmt"

	"github.com/zoncoen/query-go"
)

type S struct {
	Maps []map[string]string
}

func main() {
	q, err := query.ParseString("Maps[0].key")
	if err == nil {
		v, _ := q.Extract(&S{
			Maps: []map[string]string{
				{"key": "value"},
			},
		})
		fmt.Println(v)

	}
}
Output:

value

func (Query) Append

func (q Query) Append(es ...Extractor) *Query

Append appends extractor to q and returns updated q.

func (*Query) Extract

func (q *Query) Extract(target interface{}) (interface{}, error)

Extract extracts the value by q from target.

func (*Query) Extractors added in v1.1.0

func (q *Query) Extractors() []Extractor

Extractors returns query extractors of q.

func (Query) Index

func (q Query) Index(i int) *Query

Index is shorthand method to create Index and appends it.

func (Query) Key

func (q Query) Key(k string) *Query

Key is shorthand method to create Key and appends it.

func (*Query) String

func (q *Query) String() string

String returns q as string.

Directories

Path Synopsis
Package ast declares the types used to represent syntax trees.
Package ast declares the types used to represent syntax trees.
extractor
protobuf Module
yaml Module
Package parser implements a parser for a query string.
Package parser implements a parser for a query string.
Package token defines constants representing the lexical tokens.
Package token defines constants representing the lexical tokens.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL