Reputation: 23
I have data coming from a request in text/plain in this format:
machine_id=XXX&v_k=44&v_dr=4.0&v_total=44.9&message="Idle Data"
How can I parse this into a struct or a map[string]string
in golang?
type Event struct {
MachineID string `json:"machine_id"`
Message string `json:"message"`
VDr float64 `json:"v_dr"`
VKeg float64 `json:"v_k"`
VTotal float64 `json:"v_total"`
}
I am looking to the equivalent of
jsonMap := make(map[string]interface{})
err = json.Unmarshal(body, &jsonMap)
or
var p Event
err := json.NewDecoder(c.Request.Body).Decode(&p)
if the raw string was json formatted. I cannot change the Header coming from the client to application/x-www-form-urlencoded
and handle this as a form.
Upvotes: 1
Views: 756
Reputation: 76
The ParseQuery
method in the url
package will do it, with the caveat that the item you have in quotes, message="Idle Data", might not parse quite right, meaning you'll want to call url.PathEscape
first.
url.ParseQuery("machine_id=XXX&v_k=44&v_dr=4.0&v_total=44.9&message=Idle+Data"))
ParseQuery returns a Values
type, which is just map[string][]string
If this is coming from an HTTP request, though. the Request object has a method to handle parsing the query string. It's Parse Form
https://play.golang.org/p/NUvrXnsPM89
Upvotes: 3