Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Binding json POSTed to a struct #156

Closed
pandex opened this issue Jul 23, 2015 · 2 comments
Closed

Binding json POSTed to a struct #156

pandex opened this issue Jul 23, 2015 · 2 comments
Assignees
Labels

Comments

@pandex
Copy link

pandex commented Jul 23, 2015

I have this json POSTed via Ajax in this valid format:

var payload = '{"x":1,"y":2,"z":3…}';

I assume the only way to get payload in echo (either as string or json) is via c.Bind(). I tried

type Payload struct {
    S string 
}

var pLoad Payload
c.Bind(&pLoad)

but that doesn't work: pLoad or pLoad.S is empty.

I can't break out each json item in the struct (x, y, z…) since it's variable. For now, I'd just like to treat {"x":1,"y":2,"z":3…} as one string which eventually goes into a DB. I don't want to do

var payload = '{"a":"{"x":1,"y":2,"z":3…}"}';

either.

How do I bind a POSTed json ({"string": "string"/number}, like '{"x":1,"y":"two","z":3…}') into a struct or variable as a single string value?

@vishr
Copy link
Member

vishr commented Jul 24, 2015

I don't think you can decode a string with no key into go struct. Looking into http://stackoverflow.com/a/7487892/197473, using just a string as JSON payload is not valid. You can send your request as text/plain and read request body into a string, like below:

if b, err := ioutil.ReadAll(c.Request().Body); err == nil {
  return string(b)
} 

@vishr vishr closed this as completed Jul 24, 2015
@vishr vishr added the question label Jul 24, 2015
@vishr vishr self-assigned this Jul 24, 2015
@pandex
Copy link
Author

pandex commented Jul 25, 2015

Thanks for the b, err := ioutil.ReadAll(c.Request().Body) tip.
That works and as I was exploring different Postgres types like bytea and json, I also used

var b map[string]int16

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants