Coder Social home page Coder Social logo

encoder's Introduction

encoder wercker status

This is a simple wrapper to the json and xml Marshallers with some filter capabilities. Unlike 'render' package it doesn't write anything, just returns marshalled byte array.

E.g.:

type Some struct {
	Login    string        `json:"login"`
	Password string        `json:"password,omitempty"`
	Avatar   string        `json:"avatar"`
}

// Adding Filter method
func (this Some) Filter() interface{} {
	this.Password = "" // will be omitted in Marshaller
	this.Avatar = "http://some-origin/" + this.Login
	return this
}

Filter method will be invoked automatically. If a slice or an array passed, for each Some structure in slice.

Example

package main

import (
	"github.com/go-martini/martini"
	"github.com/martini-contrib/encoder"
	"log"
	"net/http"
	"strconv"
)

type Some struct {
	Login    string `json:"login"`
	Password string `json:"password,omitempty" xml:",omitempty"`
	Url      string `json:"url"`
}

func (this Some) Filter() interface{} {
	this.Password = ""
	this.Url = "http://some-origin/" + this.Login
	return this
}

func init() {
	log.SetFlags(log.Lshortfile)
}

func main() {
	m := martini.New()
	route := martini.NewRouter()

	m.Use(func(c martini.Context, w http.ResponseWriter, r *http.Request) {
		// Use indentations. &pretty=1
		pretty, _ := strconv.ParseBool(r.FormValue("pretty"))
		// Use null instead of empty object for json &null=1
		null, _ := strconv.ParseBool(r.FormValue("null"))
		// Some content negotiation
		switch r.Header.Get("Content-Type") {
		case "application/xml":
			c.MapTo(encoder.XmlEncoder{PrettyPrint: pretty}, (*encoder.Encoder)(nil))
			w.Header().Set("Content-Type", "application/xml; charset=utf-8")
		default:
			c.MapTo(encoder.JsonEncoder{PrettyPrint: pretty, PrintNull: null}, (*encoder.Encoder)(nil))
			w.Header().Set("Content-Type", "application/json; charset=utf-8")
		}
	})

	route.Get("/user", func(enc encoder.Encoder) (int, []byte) {
		result := Some{"user1", "passwordhash", "/user1"}
		return http.StatusOK, encoder.Must(enc.Encode(result))
	})

	route.Get("/users", func(enc encoder.Encoder) (int, []byte) {
		result := []Some{
			Some{"user1", "somehash", "/user1"},
			Some{"user2", "somehash", "/user2"},
		}

		return http.StatusOK, encoder.Must(enc.Encode(result))
	})

	m.Action(route.Handle)

	log.Println("Waiting for connections...")

	if err := http.ListenAndServe(":8000", m); err != nil {
		log.Fatal(err)
	}
}

So, the result will be as follows:

~ curl -XGET http://localhost:8000/users\?pretty\=1\&null\=1
[
    {
        "login": "user1",
        "url": "http://some-origin/user1"
    },
    {
        "login": "user2",
        "url": "http://some-origin/user2"
    }
]

encoder's People

Contributors

3d0c avatar codegangsta avatar jakejscott avatar mmigacz avatar ranveerkunal avatar regadas avatar seanmcn avatar tomharris avatar zackbloom avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

encoder's Issues

out:"false" doesn't hide in struct slice

If you have struct like this, the password will be shown.

type Some struct {
    Login    string `json:"login"`
    Password string `json:"password" out:"false"`
}

type SomeData struct {
    SomeSl []Some `json:"some"`
}

......

    route.Get("/test", func(enc encoder.Encoder) (int, []byte) {
            result := &SomeData{[]Some{
                Some{"awesome", "hidden"},
                Some{"awesome2", "hidden2"},
            }}

            return http.StatusOK, encoder.Must(enc.Encode(result))
        })

Panic when encoding struct with value of type time.Time

I tried to encode a Struct with a value of type time.Time.
When doing so through the encoder package I get a Panic returned. When I marshall it directly through the json package I get the desired result.

I am not deep enough into reflection yet to see where exactly the problem is, so every help is much appreciated, thanks!

Reproduction Code:

package main

import (
    "encoding/json"
    "github.com/go-martini/martini"
    "github.com/martini-contrib/encoder"
    "net/http"
    "time"
)

type Foo struct {
    CreatedAt time.Time `json:"createdAt"`
}

func main() {
    m := martini.Classic()

    m.Get("/doesntwork", DoesntWork)
    m.Get("/doeswork", DoesWork)
    m.Run()
}

func DoesntWork() (int, []byte) {
    foo := Foo{CreatedAt: time.Now()}
    enc := encoder.JsonEncoder{}
    return http.StatusOK, encoder.Must(enc.Encode(foo))
}

func DoesWork() (int, []byte) {
    foo := Foo{CreatedAt: time.Now()}
    data, _ := json.Marshal(foo)
    return http.StatusOK, data
}

Panic in case of /doesntwork:

[martini] PANIC: reflect: reflect.Value.Set using value obtained using unexported field
/usr/local/go/src/pkg/reflect/value.go:265 (0x91a2b)
    flag.mustBeAssignable: panic("reflect: " + methodName() + " using value obtained using unexported field")
/usr/local/go/src/pkg/reflect/value.go:1379 (0x962e7)
    Value.Set: v.mustBeAssignable()
/go/src/github.com/martini-contrib/encoder/encoder.go:133 (0x3c1c6)
    copyStruct: result.Field(i).Set(iterateSlice(vfield))
/go/src/github.com/martini-contrib/encoder/encoder.go:121 (0x3c1de)
    copyStruct: r := copyStruct(vfield)
/go/src/github.com/martini-contrib/encoder/encoder.go:121 (0x3c1de)
    copyStruct: r := copyStruct(vfield)
/go/src/github.com/martini-contrib/encoder/encoder.go:56 (0x3ba1c)
    JsonEncoder.Encode: result = copyStruct(reflect.ValueOf(data)).Interface()
/go/src/github.com/ntboes/martini-time-binding-panic/server.go:26 (0x22bc)
    DoesntWork: return http.StatusOK, encoder.Must(enc.Encode(foo))
/usr/local/go/src/pkg/runtime/asm_amd64.s:339 (0x24f02)
    call32: CALLFN(call32, 32)
/usr/local/go/src/pkg/reflect/value.go:474 (0x92d9b)
    Value.call: call(fn, ptr, uint32(size))
/usr/local/go/src/pkg/reflect/value.go:345 (0x91e8d)
    Value.Call: return v.call("Call", in)
/go/src/github.com/codegangsta/inject/inject.go:102 (0xc8b24)
    (*injector).Invoke: return reflect.ValueOf(f).Call(in), nil
/go/src/github.com/go-martini/martini/env.go:1 (0x384ac)
    (*context).Invoke: package martini
/go/src/github.com/go-martini/martini/router.go:322 (0x36134)
    (*routeContext).run: vals, err := r.Invoke(handler)
/go/src/github.com/go-martini/martini/router.go:225 (0x35724)
    (*route).Handle: context.run()
/go/src/github.com/go-martini/martini/router.go:112 (0x34780)
    (*router).Handle: route.Handle(context, res)
/go/src/github.com/go-martini/martini/martini.go:111 (0x369c0)
    Router.Handle.fm: m.Action(r.Handle)
/usr/local/go/src/pkg/runtime/asm_amd64.s:340 (0x24f62)
    call64: CALLFN(call64, 64)
/usr/local/go/src/pkg/reflect/value.go:474 (0x92d9b)
    Value.call: call(fn, ptr, uint32(size))
/usr/local/go/src/pkg/reflect/value.go:345 (0x91e8d)
    Value.Call: return v.call("Call", in)
/go/src/github.com/codegangsta/inject/inject.go:102 (0xc8b24)
    (*injector).Invoke: return reflect.ValueOf(f).Call(in), nil
/go/src/github.com/go-martini/martini/martini.go:165 (0x32d82)
    (*context).run: _, err := c.Invoke(c.handler())
/go/src/github.com/go-martini/martini/martini.go:156 (0x32cdb)
    (*context).Next: c.run()
/go/src/github.com/go-martini/martini/recovery.go:140 (0x36ee6)
    func.004: c.Next()
/usr/local/go/src/pkg/runtime/asm_amd64.s:339 (0x24f02)
    call32: CALLFN(call32, 32)
/usr/local/go/src/pkg/reflect/value.go:474 (0x92d9b)
    Value.call: call(fn, ptr, uint32(size))
/usr/local/go/src/pkg/reflect/value.go:345 (0x91e8d)
    Value.Call: return v.call("Call", in)
/go/src/github.com/codegangsta/inject/inject.go:102 (0xc8b24)
    (*injector).Invoke: return reflect.ValueOf(f).Call(in), nil
/go/src/github.com/go-martini/martini/martini.go:165 (0x32d82)
    (*context).run: _, err := c.Invoke(c.handler())
/go/src/github.com/go-martini/martini/martini.go:156 (0x32cdb)
    (*context).Next: c.run()
/go/src/github.com/go-martini/martini/logger.go:16 (0x36779)
    func.001: c.Next()
/usr/local/go/src/pkg/runtime/asm_amd64.s:340 (0x24f62)
    call64: CALLFN(call64, 64)
/usr/local/go/src/pkg/reflect/value.go:474 (0x92d9b)
    Value.call: call(fn, ptr, uint32(size))
/usr/local/go/src/pkg/reflect/value.go:345 (0x91e8d)
    Value.Call: return v.call("Call", in)
/go/src/github.com/codegangsta/inject/inject.go:102 (0xc8b24)
    (*injector).Invoke: return reflect.ValueOf(f).Call(in), nil
/go/src/github.com/go-martini/martini/martini.go:165 (0x32d82)
    (*context).run: _, err := c.Invoke(c.handler())
/go/src/github.com/go-martini/martini/martini.go:69 (0x320a3)
    (*Martini).ServeHTTP: m.createContext(res, req).run()
/usr/local/go/src/pkg/net/http/server.go:1597 (0x4fa8e)
    serverHandler.ServeHTTP: handler.ServeHTTP(rw, req)
/usr/local/go/src/pkg/net/http/server.go:1167 (0x4da97)
    (*conn).serve: serverHandler{c.server}.ServeHTTP(w, w.req)
/usr/local/go/src/pkg/runtime/proc.c:1394 (0x18b70)
    goexit: runtime·goexit(void)```

"out" flag does not apply for interface{}

type A struct {
    field string `json:"foo" out":false`
}

type B struct {
    field string `json:"bar"`
    result interface{} `json:"result"`
}

type C struct {
    field string `json:"baz"`
    result A `json:"result"`
}

// 'out' flag is ignored, A's "field" value is displayed
resultB := &B{"hello", &A{"hidden"}} 
encoder.Must(enc.Encode(resultB))

// 'out' flag is honoured, A's "field" value remains hidden
resultC := &C{"hello", A{"hidden"}} 
encoder.Must(enc.Encode(resultC))

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.