Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing Array Post Form Data in Go

Tags:

html

post

forms

go

So I have this form:

<form method="POST" action="/parse">
    <div>   
        <input name="photo[0]" value="Hey I'm photo zero!" />
    </div>
    <div>
        <input name="photo[1]" value="Photo one here!" />
    </div>
    <div>
        <input name="photo[2]" value="Awh I'm photo 2 but I'm the third photo..." />
    </div>
    <div>
        <button type="submit">submit</button>
    </div>
</form>

In Go, it appears, the net/http library will allow you to query the form data one at a time by string key in the form:

r.PostFormValue("photo[0]")

Is there an easy way to parse this form directly as a slice in Go?

That is, being able to access the elements of photo like this:

photos := r.PostFormValue("photo");
log.Println(photos[1]);

Or any other suggestion on properly accessing 'array like' data structures in form post data in Golang aside from string munging...

like image 560
BlinkyTop Avatar asked Sep 04 '25 01:09

BlinkyTop


1 Answers

Don’t add array index in name, use same name for all inputs. The http library will parse field with the same name to a slice.

<form method="POST" action="/parse">
    <div>   
        <input name="photo" value="Hey I'm photo zero!" />
    </div>
    <div>
        <input name="photo" value="Photo one here!" />
    </div>
    <div>
        <input name="photo" value="Awh I'm photo 2 but I'm the third photo..." />
    </div>
    <div>
        <button type="submit">submit</button>
    </div>
</form>
like image 129
chendesheng Avatar answered Sep 06 '25 23:09

chendesheng