Tuesday, 15 July 2014

Auto parse parameter JSON in Revel (Golang) -



Auto parse parameter JSON in Revel (Golang) -

revel doesn't parse json parameter when content type "application/json".

how enforce ?

example :

http://localhost:9000/foundations in post phone call foundations.create function. function utilize fmt.println("params :", c.params) check parameters

ruby post json data

#!/usr/bin/env ruby require "rubygems" require "json" require "net/https" uri = uri.parse("http://localhost:9000/foundations") http = net::http.new(uri.host, uri.port) header = { "content-type" => "application/json" } req = net::http::post.new(uri.path, header) req.body = { "data" => "mysurface" }.to_json() res = http.start { |http| http.request(req) }

the debug print params : &{map[] map[] map[] map[] map[] map[] []}

and when utilize none "application/json" : curl -f 'data=mysurface' http://127.0.0.1:9000/foundations

the print : params : &{map[data:[mysurface]] map[] map[] map[] map[data:[mysurface]] map[] []}

the issue json, there no way revel handle in same way "normal" post request. normally, can bind each param map[string]string object. json, has able handle arrays , nested objects, , there no way of doing without knowing beforehand construction of json be.

so solution, handle - should know fields expect, create struct fields, , json.unmarshal it.

import ( "encoding/json" "fmt" ) type surface struct { info string `json:"data"` //since have export field //but want lowercase letter } func (c mycontroller) action() revel.result { var s surface err := json.unmarshal([]byte(c.request.body), &s) fmt.println(s.data) //mysurface }

if don't using json:"data" tag or don't want export field, write own unmarshaljson function

type surface struct { info string `json:"data"` //can utilize unexported field //since handle json ourselves } func (s *structure) unmarshaljson(data []byte) error { if (s == nil) { homecoming errors.new("structure: unmarshaljson on nil pointer") } var fields map[string]string json.unmarshal(data, &fields) *s.data = fields["data"] homecoming nil }

json parameters go httprequest revel

No comments:

Post a Comment