JsonX

package module
v0.0.0-...-44dab43 Latest Latest
Warning

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

Go to latest
Published: Jan 11, 2019 License: MIT Imports: 19 Imported by: 73

README

JsonX - JSON extended for configuration files and human use

I really like JSON but it has a few problems. JsonX is a system that is intended to address these problems. JsonX is an extended JSON language specifically designed for:

  1. Humans to create and edit
  2. Configuration Files
  3. More readable syntax
  4. Syntactic error recovery
  5. Validation of input

Like most software this was developed to solve a specific set of pain points.

  1. An open source project that allowed syntactically invalid input to result in an irreversible configuration. Data was sent to browsers that is both incorrect and will be cached for 10 years.
  2. Lack of comments inside JSON. I am just not fond of languages that lack the ability to add clear documentation.
  3. Lack of decent error messages. Syntax errors and the most common use of JSON in Go (the built in package) leads to the error message "You have a syntax error" without any meaningful indication of where that syntax error may lie. The last time I used a software language like that was Fortran 66.
  4. The failure of JSON parsers to actually follow the JSON specification. Yes Go's JSON parser has some irritating errors just like most other JSON parsers.
  5. The lack of any "time" based data in JSON.

Examples

  1. ./example/simple - A simple example with of reading in a .jsonx file.
  2. ./example/ex2 - An example that uses gfDefauilt and isSet with ints
  3. ./example/ex3 - The ex2 example modified for strings with input demonstrating different quotes.

Quick Overview

In Go code


	import (
		"www.2c-why.com/JsonX"
	)

Then to read in a JsonX file and unmarsal it:

	fn := "file.jsonx"
	meta, err := JsonX.UnmarshalFile(fn, &TheDataConverted)
	if err != nil {
		fmt.Fprintf(os.Stderr, "An error in reading or unmarshaling the file %s as JsonX: %s", fn, err )
		os.Exit(1)
	}
	_ = meta // needed to validate and check for missing values!

Exampel 1

Read a configuration file.


type ClsCfgType struct {
	Id    string `gfJsonX:"id"`
	Title string `gfJsonX:"title"`
	Desc  string `gfJsonX:"desc"`
}

func ReadClsCfg(cfg *CfgType, fn string) (clsCfg ClsCfgType, err error) {
	In, err := ioutil.ReadFile(fn)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Unable to open %s for cls-config, error=%s\n", fn, err)
		return
	}

	meta, err := JsonX.Unmarshal(fn, In, &clsCfg)
	if err != nil {
		fmt.Fprintf(os.Stderr, "JxCli: Error returned from Unmarshal: %s\n", err)
		return
	}

	err = JsonX.ValidateValues(&clsCfg, meta, "", "", "")
	if err != nil {
		// print out some useful error message at this point includeing "err"
		return
	}

	// Test ValidateRequired - both success and fail, nested, in arrays
	errReq := JsonX.ValidateRequired(&clsCfg, meta)
	if errReq != nil {
		// print out some useful error message including errReq
		fmt.Printf("err=%s meta=%s\n", err, JsonX.SVarI(meta))
		msg, err := JsonX.ErrorSummary("text", &clsCfg, meta)
		if err != nil {
			fmt.Printf("%s\n", msg)
			return clsCfg, err
		}
		return clsCfg, errReq
	}

	return
}

The configuration file

{
	title: "An introduction to programming using Go"
	desc: "A beginning programming class using Go(golang)."
}

Note that "tags" inside the has need not be quoted and that commons are optional.

Exampel 2

Comments

Comments start with a // to end of line or a /* until the next */. You can configure the multi-line comments to nest.

File inclusion

You can include files from the .jx (JsonX) files. For Example:

{
	IncC: {{ __include__ ./dir/a.file }}
}

Where the directory ./dir contains a.file. the {{...}} will be replaced with the contents of the include file. Note: The paths are relative to where the file is, so ./ for the top file, then if a.file includes another file, say b.file it will be relative to the location of a.file.

File inclusion is processed at a low level, below the level of the scanner. This means that you should be able to include files at any location in the input.

Buitin Functions

From: scan.go:

	rv.Funcs["__include__"] = fxInclude
	rv.Funcs["__sinclude__"] = fxInclude
	rv.Funcs["__require__"] = fxInclude
	rv.Funcs["__srequire__"] = fxInclude
	rv.Funcs["__file_name__"] = fxFileName
	rv.Funcs["__line_no__"] = fxLineNo
	rv.Funcs["__col_pos__"] = fxColPos
	rv.Funcs["__now__"] = fxNow // the current date time samp
	rv.Funcs["__q__"] = fxQ     // return a quoted empty string
	rv.Funcs["__start_end_marker__"] = fxStartEndMarker
	rv.Funcs["__comment__"] = fxComment
	rv.Funcs["__comment_nest__"] = fxCommentNest
	rv.Funcs["__env__"] = fxEnv

TODO - document each of the builtin functions

Template processing

Pulling Defaults/Values from Environemnt

{{ __env__ Name Name Name }}

Pulls in values from the environment so that you can substitute them into your input.


$ export DB_PASS=mypassword

Then

{{ __env__ DB_PASS }}

Will substitute in the database password, mypassword. If you need to substitute this into a string then use """ quotes. See JxCli/testdata/test0021.jx for example.

Default From Environment

You can set the default value for a struct from the environment also.

type SomeStruct struct {
	Field string `gfDefaultEnv:"DB_PASS"`
}

Will pull DB_PASS from the environment and use the value of that for the default.

Pulling Defaults/Values from Redis

Setting Default Values Using Tags

A number of tags can be used to set default values inside structures. These are: gfDefault, gfDefaultEnv, gfDefaultFromKey, gfAlloc.

For example:

	type Example01 struct {
		AnInt	int		`gfDefault:"22"`
		AString	string	`gfDefault:"yep"`
		ABool	bool	`gfDefault:"true"`
		AFloat	float	`gfDefault:"2.2"`
	}
	var example01 Example01
	...
	meta := make(map[string]MetaInfo)
	err := SetDefaults(&example01, meta, "", "", "")

Will set AnInt to a value of 22, AString to yep, ABool to true and AFloat to 2.2. At first glance this seems like a difficult and complex way to set default values. However this allows for setting of default values wen the data is read in from a JsonX file.

To pull a value from the environment:

	type Example02 struct {
		DatabasePassword	string		`gfDefaultEnv:"DB_PASS"`
	}
	...
	var example02 Example02
	...
	meta := make(map[string]MetaInfo)
	meta, err := JsonX.UnmarshalFile(fn, &example02)
	...

Reading in JsonX Data

TODO

JsonX Tags

The following tags are supported.

Tag Description
gfDefault Default value for field.
gfDefaultEnv Name of environment variable to use for default if not set.
gfDefaultFromKey Key passed to PullFromDefault to get default value if not set
gfAlloc Allocate a minimum of N items in a slice.
gfPromptPassword Prompt stdin for a password to fill in field.
gfPromp Prompt stdin for a value to fill in field.
gfType A validation type, int, money, email, url, filepath, filename, fileexists
gfMinValue Inclusive minimum value for field, int, float or string.
gfMaxValue Inclusive maximum value for field, int, float or string.
gfListValue Value must come from list supplied.
gfValieRE Regular expression must match value to be valid.
gfIgnoreDefault If a default value is used then validation will not be applied.
gfRequired Must be supplied, can not be left empty.
gfTag Match name for field.
gfNoSet If "-" then will not be set. Like 1st item in json tag.

Documentation

Overview

JSONX scanner Copyright (C) Philip Schlump, 2014-2017

JSONX scanner Copyright (C) Philip Schlump, 2014-2017

package SetStruct

Index

Constants

This section is empty.

Variables

View Source
var Db map[string]bool
View Source
var DebugFlagPrintTypeLookedUp bool
View Source
var ErrDefaultsNotSet = errors.New("Defaults were not set")
View Source
var ErrDuplicateExtra = errors.New("More than one field was marked as 'extra'.  Only 1 allowed.")
View Source
var ErrFound = errors.New("Error Found")
View Source
var ErrMissingRequiredValues = errors.New("Missing Required Values")
View Source
var ErrNotSet = errors.New("Value was not set, not a settable field.")
View Source
var PerTypeValidator map[string]TypeValidator
View Source
var PostCreateMap map[string]PostCreate
View Source
var PreCreateMap map[string]PreCreate
View Source
var ValidGfNames = []string{
	"gfDefault",
	"gfDefaultEnv",
	"gfDefaultFromKey",
	"gfIgnore",
	"gfAlloc",
	"gfType",
	"gfMinValue",
	"gfMaxValue",
	"gfMinLen",
	"gfMaxLen",
	"gfListValue",
	"gfValidRE",
	"gfIgnoreDefault",
	"gfRequired",
	"gfTag",
	"gfNoSet",
	"gfJsonX",
	"gfPrompt",
	"gfPromptPassword",
}

Functions

func AppendError

func AppendError(meta map[string]MetaInfo, metaName, msg string)

func AppendErrorSetBy

func AppendErrorSetBy(meta map[string]MetaInfo, metaName, msg string)

func AssignParseTreeToData

func AssignParseTreeToData(f interface{}, meta map[string]MetaInfo, from *JsonToken, xName, topTag, path string) (err error)

func CheckGfNamesValid

func CheckGfNamesValid(tag string) (rv bool, badTag string)

func ErrorSummary

func ErrorSummary(format string, f interface{}, meta map[string]MetaInfo) (msg string, err error)

ErrorSummary Returns a summary of any errors in meta - formatted for output. If no errors then err will be nil, else ErrFound == h"Error Found" will be returned.

format == "text" Format into text for a log file or output to the screen. format == "color" Format for output in color to a screen format == "json" Format in JSON for output to a log expecing a JSON object.

TODO test

func Exists

func Exists(name string) bool

func FindOptPrefix

func FindOptPrefix(prefix string, jNopt []string) (rv string, found bool)

FindOptPrefix looks in the array of parsed options for an tag staring with "prefix". If it is found then found is true and the stuff after prefix is returned. Example: "setField:" is the prefix, then an option of "setField:MyName" will return true and "MyName".

func Fopen

func Fopen(fn string, mode string) (file *os.File, err error)

func GenArrayPath

func GenArrayPath(path, name string, idx int) (rv string)

newPath := genArrayPath(path, name, ii)

func GenStructPath

func GenStructPath(path, name string) (rv string)

newPath := genPath ( path, "struct", name )

func GetCurrentWorkingDirectory

func GetCurrentWorkingDirectory() string

func GetFilenames

func GetFilenames(dir string, rec bool) (filenames, dirs []string)

func GetHostName

func GetHostName() string

func GetTopTag

func GetTopTag(tag, tagName string) (rv string)

func GetUsedCap

func GetUsedCap(alloc string) (used, cap int)

func GetVv

func GetVv(xName, path string, meta map[string]MetaInfo, topTag string) (req bool, typ_s, minV_s, maxV_s, minLen_s, maxLen_s, list_s, valRe_s string, ignoreDefault bool, name, metaName string)

func InArray

func InArray(lookFor string, inArr []string) bool

func IntMax

func IntMax(a, b int) int

func IntMin

func IntMin(a, b int) int

func InterfaceSlice

func InterfaceSlice(slice interface{}) []interface{}

TODO test InterfaceSlice converts from a interface that refers to a slize to an array of interfaces with each one refering to one element in the slice. An example of using it is:

ss := InterfaceSlice(f.Interface())
for ii, vv := range ss {
	fmt.Printf("at %d %v\n", ii, vv)
}

From: http://stackoverflow.com/questions/12753805/type-converting-slices-of-interfaces-in-go

func MatchName

func MatchName(jNname, colName, jsonXattrName string) bool

jNname The name specified from the tag. '*' - means use column name match. colName The name of the data column in the structure jsonXattrName The name of the attribugte in the JSON dictionary

func OptIsFound

func OptIsFound(opt []string) bool

func OptNoTypeError

func OptNoTypeError(opt []string) bool

func OptOmitEmpty

func OptOmitEmpty(opt []string) bool

func OptSetField

func OptSetField(jNname, name string, from *JsonToken, jNopt []string, val reflect.Value, source SetByType)

func OptString

func OptString(opt []string) bool

func OptTypeOf

func OptTypeOf(opt []string) bool

func OptUnused

func OptUnused(opt []string) bool

func ParseGfJsonX

func ParseGfJsonX(jN string) (name string, opt []string)

jNname, jNalt := ParseGfJsonX(jN) "Name,options..." Options are:

is-found		true/false if data value is found
no-type-error	ignore type errors to int<-string results in no error (allows for multiple type values)
type-of			return the "type" of the RValue
*,unused		take all the unused values and assign to this one.
*,omitempty		On Marshall - if field is NULL then omit it.

func ParseLineIntoWords

func ParseLineIntoWords(line string) []string

func PrintJsonToken

func PrintJsonToken(data []JsonToken)

func PrintTokenSlice

func PrintTokenSlice(data []JsonToken, depth int)

func ProcessPath

func ProcessPath(js *JsonXScanner, fn string) (outFn []string, found bool)

func SVar

func SVar(v interface{}) string

SVar convert a variable to it's JSON representation and return

func SVarI

func SVarI(v interface{}) string

SVarI convert a variable to it's JSON representation with indendted JSON

func SearchArrayTooMany

func SearchArrayTooMany(jNname, colName string, from *JsonToken, maxPos int) (nSupp int, ok bool)

NChild := SearchArrayNChild(jNname, name, from) if nSupp, ok := SearchArrayTooMany(jName, name, from, f.Len()); !ok {

func SearchBool

func SearchBool(jNname, colName string, from *JsonToken) (dv bool, ok bool, fn string, ln int)

func SearchBoolTop

func SearchBoolTop(jNname, colName string, from *JsonToken) (dv bool, ok bool, fn string, ln int)

dvb, ok, fn, ln := SearchBoolTop(jNname, name, from)

func SearchFloat

func SearchFloat(jNname, colName string, from *JsonToken) (dv float64, ok bool, fn string, ln int)

func SearchFloatTop

func SearchFloatTop(jNname, colName string, from *JsonToken) (dv float64, ok bool, fn string, ln int)

func SearchInt

func SearchInt(jNname, colName string, from *JsonToken) (dv int64, ok bool, fn string, ln int)

func SearchIntTop

func SearchIntTop(jNname, colName string, from *JsonToken) (dv int64, ok bool, fn string, ln int)

func SearchString

func SearchString(jNname, colName string, from *JsonToken) (dv string, ok bool, fn string, ln int)

Example Call:

dv, ok := SearchString(jNname, from)

func SearchStringTop

func SearchStringTop(jNname, colName string, from *JsonToken) (dv string, ok bool, fn string, ln int)

func SetDataSource

func SetDataSource(meta map[string]MetaInfo, metaName string, ds SetByType)

func SetDataSourceFnLn

func SetDataSourceFnLn(meta map[string]MetaInfo, metaName string, ds SetByType, fn string, ln int)

func SetDebugFlag

func SetDebugFlag(name string, onOff bool)

func SetDebugFlags

func SetDebugFlags(flags string)

func SetDefaults

func SetDefaults(f interface{}, meta map[string]MetaInfo, xName, topTag, path string) (err error)

func StringsAfter

func StringsAfter(s, sep string) string

func StringsBefore

func StringsBefore(s, sep string) string

func StringsDeQuote

func StringsDeQuote(str string) (rv string)

func TokenToErrorMsg

func TokenToErrorMsg(data *JsonToken) (rv []string)

TokenToErrorMsg returns an array of strings that contains any error messages from the scan/parse process. These are the errors in the syntax tree.

func Unmarshal

func Unmarshal(Src string, In []byte, Out interface{}) (meta map[string]MetaInfo, err error)

func UnmarshalFile

func UnmarshalFile(fn string, Out interface{}) (meta map[string]MetaInfo, err error)

func UnmarshalString

func UnmarshalString(Src, In string, Out interface{}) (meta map[string]MetaInfo, err error)

func ValidateRequired

func ValidateRequired(f interface{}, meta map[string]MetaInfo) (err error)

func ValidateValues

func ValidateValues(f interface{}, meta map[string]MetaInfo, xName, topTag, path string) (err error)

Types

type ChildType

type ChildType int
const (
	OnlyInt    ChildType = 1
	OnlyFloat  ChildType = 2
	OnlyBool   ChildType = 3
	OnlyString ChildType = 4
	OnlyMany   ChildType = 5
)

func DeriveArrayType

func DeriveArrayType(from *JsonToken) (dType ChildType)

godebug.Db2Printf(db120, "%s Could be of type %s, %s%s\n", MiscLib.ColorYellow, DeriveArrayType(from), godebug.LF(), MiscLib.ColorReset)

func DeriveObjectType

func DeriveObjectType(from *JsonToken) (dType ChildType)

godebug.Db2Printf(db120, "%s Could be of type %s, %s%s\n", MiscLib.ColorYellow, DeriveObjectType(from), godebug.LF(), MiscLib.ColorReset)

func (ChildType) String

func (ct ChildType) String() (rv string)

type ErrorItem

type ErrorItem struct {
	Code        int
	Msg         string
	FileName    string
	LineNo      int
	ColPos      int
	GeneratedAt string
}

type FileSource

type FileSource struct {
}

func NewFileSource

func NewFileSource() *FileSource

func (*FileSource) Exists

func (fs *FileSource) Exists(fn string) (rv bool)

Exists returns true if the speified name, 'fn', exists and is an appropriate type of object to open and read from.

func (*FileSource) ReadFile

func (fs *FileSource) ReadFile(fn string) (buf []byte, err error)

type JsonScannerInputStack

type JsonScannerInputStack struct {
	Pos      int    // where in buf
	LineNo   int    // Current Line number
	ColPos   int    //
	FileName string // Current File Name
	Buf      []byte // the input text in memory
}

type JsonToken

type JsonToken struct {
	Number       int
	TokenNo      TokenType
	TokenNoValue TokenType
	Name         string
	Value        string
	NValue       int
	FValue       float64
	IValue       int64
	BValue       bool
	LineNo       int
	ColPos       int
	FileName     string
	ErrorMsg     string
	Children     []JsonToken
	GeneratedAt  string
	UsedData     bool     // used in assignment, true if this value has been used.
	AssignedTo   []string // List of who this value was assigned to.
}

func NameValueNode

func NameValueNode(name JsonToken, ptr JsonToken) (rv JsonToken)

func NameValueNodeNullError

func NameValueNodeNullError(name JsonToken) (rv JsonToken)

func ParseJsonX

func ParseJsonX(buf []byte, js *JsonXScanner) (rv *JsonToken, NErrors int)

func SearchArray

func SearchArray(jNname, colName string, from *JsonToken, arrPos int) (dv *JsonToken, ok bool)

newFrom, ok := SearchArray(jNname, name, from, ii) // ok is false if array-subscript, 'ii' is out of range

func SearchHashLength

func SearchHashLength(jNname, colName string, from *JsonToken) (nSupp int, fromHash *JsonToken)

NInHash := SearchHashLength(jNname, name, from)

func SearchHashValue

func SearchHashValue(from *JsonToken, ii int) (ok bool, key string, rawValue *JsonToken)

keyString, rawValue := SearchHashValue(jNname, name, from, ii) // - # of children in TokenObjectStart > 0, if so then allocate SearchHashLength must be run first to pick out 'from' from the original data. // func SearchHashValue(jNname, colName string, from *JsonToken, ii int) (ok bool, key string, rawValue *JsonToken) {

func SearchStruct

func SearchStruct(jNname, colName string, from *JsonToken) (dv *JsonToken, ok bool)

newFrom, ok := SearchStruct(jNname, name, from)

type JsonXConfig

type JsonXConfig struct {
	FirstInWins     bool     `gfDefault:"false"`  // used by this file
	TopName         string   `gfDefault:""`       // used by this file - the name for things that are not in a struct.
	OutputLineWidth int      `gfDefault:"120"`    // max number of chars, 0 indicates output should go down page.
	OutputInJSON    bool     `gfDefault:"false"`  //
	InputPath       []string `gfDefault:"['./']"` // Path to use for searching for files for __include__, __require__
}

This single config

func NewJsonX

func NewJsonX() (rv *JsonXConfig)

func (*JsonXConfig) AssignParseTreeToData

func (jx *JsonXConfig) AssignParseTreeToData(f interface{}, meta map[string]MetaInfo, from *JsonToken, xName, topTag, path string) (err error)

Assign to 'f' the data from 'from'. Keep an ongoing 'path' as we make recursive calls. 'meta' is data from setting defauls on the top level - overwrite data in it as we assing data to stuff in 'f'.

func (*JsonXConfig) GetDv

func (jx *JsonXConfig) GetDv(xName, path string, meta map[string]MetaInfo, topTag string) (dv, name, metaName string)

func (*JsonXConfig) SetDefaults

func (sd *JsonXConfig) SetDefaults(f interface{}, meta map[string]MetaInfo, xName, topTag, path string) (err error)

SetDefaults uses a set of tags to set default values and allocate storage inside a structure.

func (*JsonXConfig) SetFirstInWins

func (jx *JsonXConfig) SetFirstInWins(b bool) *JsonXConfig

chainable

func (*JsonXConfig) SetTopName

func (jx *JsonXConfig) SetTopName(s string) *JsonXConfig

chainable -- name

func (*JsonXConfig) ValidateRequired

func (vr *JsonXConfig) ValidateRequired(f interface{}, meta map[string]MetaInfo) (err error)

ValidateRequired is a final check - after other processing that required values are set.

func (*JsonXConfig) ValidateValues

func (vl *JsonXConfig) ValidateValues(f interface{}, meta map[string]MetaInfo, xName, topTag, path string) (err error)

ValidateValues uses tags on the structures to validate the values that are in the structure. Special tags are allowed for non-validation of default values thereby allowing for defauts that are not valid data.

type JsonXFunc

type JsonXFunc func(js *JsonXScanner, args []string) (rv string)

type JsonXInput

type JsonXInput interface {
	ReadFile(fn string) ([]byte, error) // Matches with ioutil.ReadFile - so for regular files can just use that in the interface
	Exists(fn string) bool              // Used with "path" processing to see if resource exists
}

type JsonXScanner

type JsonXScanner struct {
	State        int                    //
	Pos          int                    // where in buf
	StateSt      []byte                 //
	LineNo       int                    // Current Line number
	ColPos       int                    // Current Col Pos
	FileName     string                 // Current File Name
	PrevLineNo   int                    // Prev Line number
	PrevColPos   int                    // Prev Col Pos
	PrevFileName string                 // Prev File Name
	Toks         []JsonToken            //
	Options      ScanOptions            //
	InputSource  JsonXInput             // the input interface, defaults to file system
	Buf          []byte                 // the input text in memory
	Funcs        map[string]JsonXFunc   // functions to process
	Data         map[string]interface{} //

	EmitNo      int    //
	PathTop     string // Current directory
	PosSaved    bool
	SavedLineNo int // Current Line number
	SavedColPos int // Current Col Pos
	// contains filtered or unexported fields
}

func NewScan

func NewScan(fn string) (rv *JsonXScanner)

func (*JsonXScanner) MapFunction

func (js *JsonXScanner) MapFunction(name string, impl JsonXFunc)

func (*JsonXScanner) PrevToken

func (js *JsonXScanner) PrevToken(offset int) (t TokenType)

if PrevToken(-2) == TokenId && PrevToken(-1) != TokenColon {

func (*JsonXScanner) ScanBytes

func (js *JsonXScanner) ScanBytes(buf []byte)

func (*JsonXScanner) ScanFile

func (js *JsonXScanner) ScanFile(fn string)

func (*JsonXScanner) ScanInput

func (js *JsonXScanner) ScanInput(fn string, source JsonXInput)

func (*JsonXScanner) ScanString

func (js *JsonXScanner) ScanString(buf string)

func (*JsonXScanner) SetCommentsNest

func (js *JsonXScanner) SetCommentsNest(ns bool) *JsonXScanner

js.SetCommentsNest(tf)

func (*JsonXScanner) SetOptions

func (js *JsonXScanner) SetOptions(opt ScanOptions) *JsonXScanner

func (*JsonXScanner) SetStartEndMarker

func (js *JsonXScanner) SetStartEndMarker(sm, em string) *JsonXScanner

type MetaInfo

type MetaInfo struct {
	LineNo   int       // if > 0 then used in formatting of error messages.
	FileName string    // if != "" then used in formatting of error messages.  Can be any string.
	ErrorMsg []string  // Error messages
	SetBy    SetByType // Who set the value the last
	DataFrom SetByType // Source of the data value
	// contains filtered or unexported fields
}

type ParserType

type ParserType struct {
	CurPos    int
	MaxPos    int
	NErrors   int
	ErrorMsgs []ErrorItem
}

func (*ParserType) AddError

func (pt *ParserType) AddError(code int, msg string, js *JsonXScanner, offset int)

func (*ParserType) AddErrorGA

func (pt *ParserType) AddErrorGA(code int, msg string, js *JsonXScanner, offset int, ga string)

func (*ParserType) AdvTok

func (pt *ParserType) AdvTok()

func (*ParserType) AdvTok2

func (pt *ParserType) AdvTok2()

func (*ParserType) ConvertValueToId

func (pt *ParserType) ConvertValueToId(name JsonToken) (rv JsonToken)

func (*ParserType) IsA

func (pt *ParserType) IsA(js *JsonXScanner, nth int, tt TokenType) bool

func (*ParserType) IsAny

func (pt *ParserType) IsAny(js *JsonXScanner, nth int) bool

func (*ParserType) IsCloseArray

func (pt *ParserType) IsCloseArray(js *JsonXScanner, nth int) bool

func (*ParserType) IsCloseHash

func (pt *ParserType) IsCloseHash(js *JsonXScanner, nth int) bool

func (*ParserType) IsId

func (pt *ParserType) IsId(js *JsonXScanner, nth int) bool

func (*ParserType) IsOpenArray

func (pt *ParserType) IsOpenArray(js *JsonXScanner, nth int) bool

func (*ParserType) IsOpenHash

func (pt *ParserType) IsOpenHash(js *JsonXScanner, nth int) bool

func (*ParserType) IsUnknown

func (pt *ParserType) IsUnknown(js *JsonXScanner, nth int) bool

func (*ParserType) IsValue

func (pt *ParserType) IsValue(js *JsonXScanner, nth int) bool

func (*ParserType) ValueCanConvertToId

func (pt *ParserType) ValueCanConvertToId(js *JsonXScanner, nth int) bool

} else if pt.IsValue(js, 0) && ValueCanConvertToId(js, 0) {

type PostCreate

type PostCreate func(in interface{}) (err error) // Called after validation(both) -- Allows for post validation processing

type PreCreate

type PreCreate func(in interface{}) (out interface{}, cp bool, err error) // Called after "tag" processing but before data is added by hjson

type PullFromFunc

type PullFromFunc func(key string) (use bool, value string)
var PullFromDefault PullFromFunc

This function can be a closure that pulls data from Redis, Etcd or some other external source.

type ScanOptions

type ScanOptions struct {
	StartMarker          string //
	EndMarker            string //
	CommentsNest         bool   //
	FirsInWins           bool
	ReportMissingInclude bool
}

type SetByType

type SetByType int
const (
	FromTag               SetByType = 0
	NotSet                SetByType = 1
	IsDefault             SetByType = 2
	UserSet               SetByType = 3
	Error                 SetByType = 4
	Alloc                 SetByType = 5
	FromEnv               SetByType = 6
	FromFunc              SetByType = 7
	ByJsonX               SetByType = 8
	FromUserInputPassword SetByType = 9
	FromUserInput         SetByType = 10
)

func (SetByType) String

func (sb SetByType) String() (rv string)

type TokenType

type TokenType int
const (
	TokenUnknown     TokenType = 0  // Hm...
	TokenObject      TokenType = 1  // on '}'
	TokenArray       TokenType = 2  // on ']'
	TokenString      TokenType = 3  // A value
	TokenId          TokenType = 4  // "name" or name before a ":"
	TokenNull        TokenType = 7  // A value
	TokenFloat       TokenType = 8  // A value
	TokenBool        TokenType = 9  // A value
	TokenInt         TokenType = 10 // A value
	TokenObjectStart TokenType = 11 // on '{'
	TokenArrayStart  TokenType = 12 // on '['
	TokenObjectEnd   TokenType = 13 // on '{'
	TokenArrayEnd    TokenType = 14 // on '['
	TokenColon       TokenType = 15 // on ':'
	TokenComma       TokenType = 16 // on ','
	TokenNameValue   TokenType = 17 // name:value in a hash
)

func (TokenType) String

func (tt TokenType) String() string

type TypeValidator

type TypeValidator func(in interface{}) (ok bool, err error) // Validate a "type", like email, money, SSN etc.

type UnmarshalType

type UnmarshalType int
const (
	UTString     UnmarshalType = 1
	UTInt        UnmarshalType = 2
	UTFloat      UnmarshalType = 3
	UTBool       UnmarshalType = 4
	UTDictionary UnmarshalType = 5
	UTArray      UnmarshalType = 6
)

type Unmarshaler

type Unmarshaler interface {
	UnmarshalJsonXString(in []byte) (out string, err error)
	UnmarshalJsonXFloat(in []byte) (out float64, err error)
	UnmarshalJsonXInt(in []byte) (out int64, err error)
	UnmarshalJsonXBool(in []byte) (out bool, err error)
}

Directories

Path Synopsis
examples
ex2
ex3
ex4

Jump to

Keyboard shortcuts

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