Question

I would like to marshal in and out of x-www-form-urlencoding similar to how you can do it with json or xml. Is there an existing package to do this, or are there any documents on how to implement one myself if none exist?

Was it helpful?

Solution

gorilla/schema is popular and well maintained:

e.g.

func FormHandler(w http.RequestWriter, r *http.Request) {

    err := r.ParseForm()
    if err != nil {
         // handle error
    }
    person := new(Person) // Person being a struct type
    decoder := schema.NewDecoder()

    err = decoder.Decode(person, r.Form)
    if err != nil {
         // handle error
    }

}

goforms is also an alternative.

Update May 23rd 2015:

  • gorilla/schema is still my pick as one of the most-supported map-to-struct packages, with POST form values being a common use-case.
  • goji/param is also fairly solid and has many of the same features.
  • mholt/binding is a little more feature packed at the (IMO) expense of a slightly more complex API.

I've been using gorilla/schema for a couple of years now and haven't had any major issues with it. I use it in conjunction with vala for validating inputs (not nil, too short, too long, etc) before they hit the DB.

OTHER TIPS

I just found https://github.com/ajg/form which is exactly what I was looking for. There is also https://github.com/gorilla/schema for strictly decoding and https://github.com/google/go-querystring for strictly encoding.

net/url seems to handle this just fine:

package main

import (
   "fmt"
   "net/url"
)

func main() {
   {
      m := url.Values{
         "CR": {"\r"}, "LF": {"\n"},
      }
      s := m.Encode()
      fmt.Println(s) // CR=%0D&LF=%0A
   }
   {
      s := "CR=%0D&LF=%0A"
      m, e := url.ParseQuery(s)
      if e != nil {
         panic(e)
      }
      fmt.Printf("%q\n", m) // map["CR":["\r"] "LF":["\n"]]
   }
}

https://github.com/google/go-querystring is good, but doesn't support maps (and slices of maps).

I started https://github.com/drewlesueur/querystring for map support. (It doesn't support structs yet, but pull requests welcome).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top