Converts go types no matter what

elastic

Build Status GoDoc

Converts go types no matter what

elastic is a simple library that converts any type to another the best way possible. This is useful when the type is only known at run-time, which usually happens when serializing data. elastic allows your code to be flexible regarding type conversion if that is what you're looking for.

It is also capable of seeing through alias types and converting slices and maps to and from other types of slices and maps, providing there is some logical way to convert them.

Default conversion can be overridden by providing custom conversion functions for specific types. Struct types can also implement the ConverterTo interface to help with conversion to and from specific types.

Quick examples:

convert value types:

	// note that using elastic wouldn't make sense if you are certain
    // f is a float64 at compile time.
    var f interface{} = float64(5.5)
	var i int
    
    err := elastic.Set(&i, f)
	if err != nil {
		log.Fatal(f)
	}

	fmt.Println(i) // prints 5

convert slices:

	var ints []int
	err = elastic.Set(&ints, []interface{}{1, 2, 3, "4", float64(5), 6})
	if err != nil {
		log.Fatal(f)
	}

	fmt.Println(ints) // prints [1 2 3 4 5 6]

convert maps:

	someMap := map[string]interface{}{
		"1": "uno",
		"2": "dos",
		"3": "tres",
	}

	intmap := make(map[int]string)
	err = elastic.Set(&intmap, someMap)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(intmap) // prints map[1:uno 2:dos 3:tres]

Simple API:

elastic.Convert()

Converts the passed value to the target type

Syntax:

elastic.Convert(source interface{}, targetType reflect.Type) (interface{}, error)

  • source: value to convert
  • targetType the type you want to convert source to

Returns

The converted value or an error if it fails.

elastic.Set()

Sets the given variable to the passed value

Syntax:

elastic.Set(target, source interface{}) error

  • target: value to set. Must be a pointer.
  • source the value to convert

Returns

Only an error if it fails.

Advanced API:

You can create different instances of the elastic conversion engine so that you can customize conversions independently

elastic.New()

Returns a new conversion engine. It has a .Set() and .Convert() as above that will work according to the rules set for this engine

AddSourceConverter() and AddTargetConverter()

Registers a conversion function for the given type, either when the type is found on the source side or the target side.

These are useful when you do not control the type you whish to make convertible

Syntax:

engine.AddSourceConverter(sourceType reflect.Type, f ConverterFunc)

  • sourceType: type you want to set a custom conversion function for
  • f: Conversion function to invoke when this type is found as a source

engine.AddTargetConverter(targetType reflect.Type, f ConverterFunc)

  • targetType: type you want to set a custom conversion function for
  • f: Conversion function to invoke when this type is found as a target

The value returned by your function does not have to be exactly of type targetType. For example if a float64 is requested and you return an integer, elastic will deal with it.

Example:

package main

type Vector struct {
	X float64
	Y float64
}

func main() {

	// Add a custom converter to convert Vector to float64 or int
	// (Calculates the modulus of the vector)
	elastic.Default.AddSourceConverter(reflect.TypeOf(Vector{}), func(source interface{}, targetType reflect.Type) (interface{}, error) {
		vector := source.(Vector)
		switch targetType.Kind() {
		case reflect.Float64, reflect.Int:
			return math.Sqrt(float64(vector.X*vector.X) + float64(vector.Y*vector.Y)), nil
		case reflect.String:
			return fmt.Sprintf("(%g, %g)", vector.X, vector.Y), nil
		}
		return nil, elastic.ErrNoConversionAvailable

	})

	v := Vector{
		X: 3.0,
		Y: 4.0,
	}

	f, err = elastic.Convert(v, reflect.TypeOf(float64(0)))
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(f) // prints 5

	var s string
	elastic.Set(&s, v)
	fmt.Println(s) // prints (3, 4)

}

ConverterTo interface

type ConverterTo interface {
	ConvertTo(targetType reflect.Type) (interface{}, error)
}

Implement this interface in your type to provide conversion to another types. This function will be invoked every time your type is on the right-hand side of a conversion. The value returned by your function does not have to be exactly of type targetType. For example if a float64 is requested and you return an integer, elastic will deal with it.

Example:

type Vector struct {
	X float64
	Y float64
}

func (v *Vector) ConvertTo(targetType reflect.Type) (interface{}, error) {
		switch targetType.Kind() {
		case reflect.Float64, reflect.Int:
			return math.Sqrt(float64(v.X*v.X) + float64(v.Y*v.Y)), nil
		case reflect.String:
			return fmt.Sprintf("(%g, %g)", v.X, v.Y), nil
		}
		return nil, elastic.ErrNoConversionAvailable
}

func main() {
	v := Vector{
		X: 3.0,
		Y: 4.0,
	}
	
	var i int
	elastic.Set(&i, v)
	fmt.Println(i) // prints 5

	var s string
	elastic.Set(&s, v)
	fmt.Println(s) // prints (3, 4)
}
Similar Resources

jsonc is a Go package that converts the jsonc format to standard json.

jsonc jsonc is a Go package that converts the jsonc format to standard json. The jsonc format is like standard json but allows for comments and traili

Nov 22, 2022

Converts a trace of Datadog to a sequence diagram of PlantUML (Currently, supports only gRPC)

Converts a trace of Datadog to a sequence diagram of PlantUML (Currently, supports only gRPC)

jigsaw Automatically generate a sequence diagram from JSON of Trace in Datadog. ⚠️ Only gRPC calls appear in the sequence diagram. Example w/ response

Jul 12, 2022

Converts your k8s YAML to a cdk8s Api Object.

kube2cdk8s Converts your k8s YAML to a cdk8s Api Object. Uses Pulumi's kube2pulumi as a base. Dependencies 1. pulumi cli 2. pulumi kubernetes provider

Oct 18, 2022

Simple go package which converts roman strings to integer

romanparse Simple go package which converts roman strings

Aug 11, 2022

golang program that simpily converts html into markdown

Simpily converts html to markdown Just a simple project I wrote in golang to convert html to markdown, surprisingly works decent for a lot of websites

Oct 23, 2021

WIP. Converts Azure Container Scan Action output to SARIF, for an easier integration with GitHub Code Scanning

container-scan-to-sarif container-scan-to-sarif converts Azure Container Scan Action output to Static Analysis Results Interchange Format (SARIF), for

Jan 25, 2022

converts f to c and c to f

temperature-converter converts f to c and c to f Example package main import ( "github.com/Omvik/temperature-converter/calcTemp" "fmt" "log" )

Nov 2, 2021

This command line converts .webarchive file to resources embed .html file

webarchive-to-singlefile This command line converts Safari's .webarchive file to complete .html. Notice Only tested on MacOS. Google Chrome required.

Dec 30, 2022

Converts a database into gorm structs and RESTful api

gen The gen tool produces a CRUD (Create, read, update and delete) REST api project template from a given database. The gen tool will connect to the d

Dec 28, 2022

Simple go script that converts csv file into a json document

csv-go-parser Simple go script that converts csv file into a json document. CSV Input: id,first_name,last_name,email,avatar,ip_address 1,Pauline,Hirth

Jun 4, 2022

Link converter service converts URLs to deeplinks or deeplinks to URLs.

Link converter Link converter service converts URLs to deeplinks or deeplinks to URLs. The service responds to the incoming request and first checks w

Dec 23, 2021

This command line converts thuderbird's exported RSS .eml file to .html file

thunderbird-rss-html This command line tool converts .html to .epub with images fetching. Install go get github.com/gonejack/thunderbird-rss-html Us

Dec 15, 2021

Converts NFAs (and DFAs) to a regular expressions using the state removal method.

nfa-to-regex: convert NFAs (and DFAs) to regular expressions An implementation of the state removal technique for converting an NFA to a regular expre

Apr 29, 2022

Converts NFAs (and DFAs) to a regular expressions using the state removal method

nfa2regex: convert NFAs (and DFAs) to regular expressions An implementation of the state removal technique for converting an NFA to a regular expressi

Apr 29, 2022

Converts a number to its English counterpart. Uses arbitrary precision; so a number of any size can be converted.

Converts a number to its English counterpart. Uses arbitrary precision; so a number of any size can be converted.

Dec 14, 2021

Converts grouped transactions in a ZKB transaction CSV (incl. details) to single transactions

ZKB Converter Converts grouped transactions in a ZKB transaction CSV (incl. deta

Dec 26, 2021

Converts an image file into various WebP images to use with img srcset

go-websizer Converts an image file into various WebP images to use with img srcset. Install $ go get github.com/pipe01/go-websizer Usage Usage of go-

Oct 7, 2021

Converts Eth2 EIP-2335 scrypt keystores to pbkdf2 keystores (and vice-versa).

eth2-keystore-converter Converts Eth2 EIP-2335 scrypt keystores to pbkdf2 keystores (and vice-versa). Usage Converting a scrypt keystore to pbkdf2 usi

May 13, 2022

wikipedia-jsonl is a CLI that converts Wikipedia dump XML to JSON Lines format.

wikipedia-jsonl wikipedia-jsonl is a CLI that converts Wikipedia dump XML to JSON Lines format. How to use At first, download the XML dump from Wikime

Dec 26, 2022
Comments
  • Fix panic if there is a nil in a map[...]interface{} value

    Fix panic if there is a nil in a map[...]interface{} value

    Quick fix for a panic if a map contains a nil value (such as map[string]interface{}{"a": nil}), nils are converted to 0/empty string. I've also added some nil values to the test. It is quite possible that the code still panics for nested maps, i have not tested that.

Some Golang types based on builtin. Implements interfaces Value / Scan and MarshalJSON / UnmarshalJSON for simple working with database NULL-values and Base64 encoding / decoding.

gotypes Some simple types based on builtin Golang types that implement interfaces for working with DB (Scan / Value) and JSON (Marshal / Unmarshal). N

Feb 12, 2022
Helper functions for the manipulation of slices of all types in Go

go-slices Unlike many other programming languages, Go doesn't provide helper functions for slices in it's core. I felt like this was quite an essentia

Jan 3, 2023
Plugs module to see different types of plug types needed in different countries, and a comparison tool between two countries plug socket types.

plugs Importing the module: go get github.com/matthewboyd/plugs "github.com/matthewboyd/plugs" How to use the module: There are two functions wi

Dec 28, 2021
Code your next Go web project with (a) Mojito! No matter if its an API or a website, go-mojito assists you with dependency injection, simple routing, custom request / response objects and template rendering
 Code your next Go web project with (a) Mojito! No matter if its an API or a website, go-mojito assists you with dependency injection, simple routing, custom request / response objects and template rendering

Go-Mojito is a super-modular library to bootstrap your next Go web project. It can be used for strict API-only purposes as well as server-side renderi

May 1, 2022
Library providing opanapi3 and Go types for store/validation and transfer of ISO-4217, ISO-3166, and other types.

go-types This library has been created with the purpose to facilitate the store, validation, and transfer of Go ISO-3166/ISO-4217/timezones/emails/URL

Nov 9, 2022
Go linter that checks types that are json encoded - reports unsupported types and unnecessary error checks

Checks types passed to the json encoding functions. Reports unsupported types and reports occations, where the check for the returned error can be omited.

Oct 7, 2022
Optional is a library that provides option types for Go types.

Option Optional is a library that provides option types for Go types. Installation Golang version 1.18 + required go get -u github.com/eatmoreapple/op

Nov 9, 2022
Converts 'go mod graph' output into Graphviz's DOT language
Converts 'go mod graph' output into Graphviz's DOT language

modgv Converts 'go mod graph' output into GraphViz's DOT language. takes no options or arguments it reads the output generated by “go mod graph” on st

Dec 22, 2022
A proxy server than converts JSON request bodies to protocol buffers
A proxy server than converts JSON request bodies to protocol buffers

Welcome to Protoxy ?? What is Protoxy? Protoxy allows you to test your REST APIs that use Protocol Buffer serialization through Postman and other API

Nov 1, 2022
converts text-formats from one to another, it is very useful if you want to re-format a json file to yaml, toml to yaml, csv to yaml, ... etc

re-txt reformates a text file from a structure to another, i.e: convert from json to yaml, toml to json, ... etc Supported Source Formats json yaml hc

Sep 23, 2022