encodingjs

package module
v0.0.0-...-4261472 Latest Latest
Warning

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

Go to latest
Published: May 11, 2015 License: MIT Imports: 4 Imported by: 0

README

golang-encodingjs

A JavaScript Unmarshaler for the Go language

Build Status Coverage Status

Usage

encodingjs.Unmarshal works similar to json.Unmarshal - pass the result of the JavaScript evaluation from otto and a reference to the target structure.

vm := otto.New()
jsresult, err := vm.Run(`a={Foo: "bar", Fubar:"bob"}; a`)
if err != nil {
	panic(err)
}
result := struct {
	Foo   string
	Fubar string
}{}
err= encodingjs.Unmarshal(jsresult, &result)
if err != nil {
	panic(err)
}
fmt.Printf("%+v\n", result)
// Output: {Foo:bar Fubar:bob}

Undefined vs. empty values

Except for pointers, it is not possible in go to differentiate between undefined and empty values. Implement the Unmarshaler interface to flag the difference if you need it.

Shortcomings

error path from otto is untested - I have not found a way to trigger these.

Documentation

Overview

A JavaScript Unmarshaler for Go

See the tests for ideas on how to translate variables between Go and JavaScript.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrArrayExpected is returned when the JS variable is not an array (i.e. for a go slice)
	ErrArrayExpected = errors.New("array expected")
	// ErrObjectExpected is returned when the JS variable is not an object (i.e. for a go map or struct)
	ErrObjectExpected = errors.New("object expected")
)

Functions

func Unmarshal

func Unmarshal(d otto.Value, result interface{}) error

Unmarshal transfers the contents of d into result.

Example
package main

import (
	"fmt"

	"github.com/martint17r/encodingjs"
	"github.com/robertkrimen/otto"
)

func main() {
	vm := otto.New()
	jsresult, err := vm.Run(`a={Foo: "bar", Fubar:"bob"}; a`)
	if err != nil {
		panic(err)
	}
	result := struct {
		Foo   string
		Fubar string
	}{}
	err = encodingjs.Unmarshal(jsresult, &result)
	if err != nil {
		panic(err)
	}
	fmt.Printf("%+v\n", result)
}
Output:

{Foo:bar Fubar:bob}

Types

type InvalidValueError

type InvalidValueError struct {
	Wanted string
	Got    otto.Value
}

InvalidValueError is returned when the js variable does not match the requirements from go

func (*InvalidValueError) Error

func (ive *InvalidValueError) Error() string

type Unmarshaler

type Unmarshaler interface {
	UnmarshalJS(d otto.Value) error
}

Unmarshaler is the interface implemented by objects that can unmarshal a JS representation of themselves.

type UnsupportedTypeError

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

UnsupportedTypeError is returned when channels and functions are given as targets

func (*UnsupportedTypeError) Error

func (ute *UnsupportedTypeError) Error() string

Jump to

Keyboard shortcuts

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