4

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...

3
  • 2
    Why the PHP tag here ? This makes the question really unclear. And what's the "this" you want to "accomplish" ? Commented Jul 20, 2014 at 10:20
  • @BlinkyTop what are you asking? Commented Jul 20, 2014 at 10:23
  • Hope that edit clarifies the question. Moving to Go from PHP and trying to get the parallels figured out. Commented Jul 20, 2014 at 10:35

1 Answer 1

4

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>
Sign up to request clarification or add additional context in comments.

4 Comments

What IF i have something like Contact[Name], Contact[Email], Contact[Message] in my html form ?
@DavidLavieri if it's only one object, just use <input name="Name"> <input name="Email"> etc.
Thanks, but I pass through scenarios where i need to divide the data (many objects) really often, you can check this, Where I explain it better stackoverflow.com/questions/34839811/…
Question asked how to handle the request in Go, not how to write an html. JS FormData supports sending arrays and objects as well, so the expected answer would be how to handle those data in the backend.

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.