1

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.

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.