Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang parse form

Tags:

go

If I have the following form setup:

{{ range $key, $value := .Scores }}
    <input id="{{$value.Id}}_rating__1" type="radio" name="rating[{{$value.Id}}]" value="-1">
    <input id="{{$value.Id}}_rating__0" type="radio" name="rating[{{$value.Id}}]" value="0">
    <input id="{{$value.Id}}_rating__2" type="radio" name="rating[{{$value.Id}}]" value="+1">
{{ end }}

How can I then extract that data correctly? Knowing that there .Scores can contain multiple structs

func categoryViewSubmit(w http.ResponseWriter, r *http.Request) {
    err := r.ParseForm()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("POST")

    fmt.Printf("%+v\n", r.Form()) // annot call non-function r.Form (type url.Values)
    fmt.Printf("%+v\n", r.FormValue("rating")) // Returns nothing
}
like image 450
woutr_be Avatar asked Feb 01 '15 03:02

woutr_be


People also ask

How can I read form data in Golang?

Golang Request GET Form Data First of all the Form is parsed using the ParseForm Method. For data sent using the GET Method, the Form Method is used to read data from the parsed form in the request.

What is Golang PostForm?

The docs: "PostForm issues a POST to the specified URL, with data's keys and values URL-encoded as the request body. The Content-Type header is set to application/x-www-form-urlencoded ."

How do you make HTTP request in Golang?

Get function is called, Go will make an HTTP request using the default HTTP client to the URL provided, then return either an http. Response or an error value if the request fails. If the request fails, it will print the error and then exit your program using os. Exit with an error code of 1 .

What is HTTP transport Golang?

58 const DefaultMaxIdleConnsPerHost = 2 59 60 // Transport is an implementation of RoundTripper that supports HTTP, 61 // HTTPS, and HTTP proxies (for either HTTP or HTTPS with CONNECT). 62 // 63 // By default, Transport caches connections for future re-use.


2 Answers

The form keys look like rating[id] where id is a value identifier. To get one of the values, call r.FormValue("rating[id]") after substituting id for an actual id value.

I suggest printing the form to see what's going on:

fmt.Printf("%+v\n", r.Form)  // No () following Form, Form is not a function

The form is an url.Values. An url.Values is a map[string][]string. You can iterate through the form as follows:

for key, values := range r.Form {   // range over map
  for _, value := range values {    // range over []string
     fmt.Println(key, value)
  }
}
like image 156
Bayta Darell Avatar answered Sep 27 '22 03:09

Bayta Darell


For others that are looking answers for this I found Gorilla's schema really helpful. It allows you to parse forms to structs and has support for arrays and nested structs. When you combine that with guregu's null package you can easily parse sructs with optional fields.

Example Go:

package models

import (
    "github.com/gorilla/schema"
    "gopkg.in/guregu/null.v3"
)

type User struct {
    Id            null.Int    `db:"id" json:"id"`
    // Custom mapping for form input "user_name" 
    Name          string      `db:"user_name" json:"user_name" schema:"user_name"`
    EmailAddress  string      `db:"email_address" json:"email_address"`
    OptionalField null.String `db:"optional_field" json:"optional_field"`
}

Example html

<form>
    <input type="text" name="user_name">
    <input type="text" name="EmailAddress">
    <input type="text" name="OptionalField">
</form>
like image 34
Henri Koski Avatar answered Sep 26 '22 03:09

Henri Koski