form icon indicating copy to clipboard operation
form copied to clipboard

Anonimous fields without prefix

Open Hamper opened this issue 8 years ago • 1 comments

Is possible parse anonimous fields without prefix if it's tag ommited or empty string (like json)?

Example:

package main

import (
	"encoding/json"
	"fmt"

	"github.com/ajg/form"
)

type T1 struct {
	X int `json:"x,omitempty" form:"x,omitempty"`
	Y int `json:"y,omitempty" form:"y,omitempty"`
}

type T2 struct {
	*T1 `json:"" form:""`
	A   int `json:"a,omitempty" form:"a,omitempty"`
	B   int `json:"b,omitempty" form:"b,omitempty"`
}

type T3 struct {
	*T1 `json:"t1" form:"t1"`
	A   int `json:"a,omitempty" form:"a,omitempty"`
	B   int `json:"b,omitempty" form:"b,omitempty"`
}

func main() {
	x := T2{&T1{1, 2}, 3, 4}
	s, _ := json.Marshal(x)
	s2, _ := form.EncodeToString(x)
	fmt.Println(string(s), s2)

	x2 := T3{&T1{1, 2}, 3, 4}
	s, _ = json.Marshal(x2)
	s2, _ = form.EncodeToString(x2)
	fmt.Println(string(s), s2)
}

Output:

{"x":1,"y":2,"a":3,"b":4} T1.x=1&T1.y=2&a=3&b=4
{"t1":{"x":1,"y":2},"a":3,"b":4} a=3&b=4&t1.x=1&t1.y=2

Second result is ok, but in first best result is "x=1&y=2&a=3&b=4"

Hamper avatar Feb 16 '17 16:02 Hamper

@Hamper, I think I agree. I'm not sure when I'll be able to implement the change, but you're welcome to open a pull request in the meantime (take a look at https://github.com/ajg/form/blob/master/encode.go#L143).

ajg avatar Feb 17 '17 05:02 ajg