Home

Awesome

qs build-status godoc

The qs package can marshal and unmarshal structs into/from url query strings. The interface of qs is very similar to that of some standard marshaler packages like encoding/json, encoding/xml.

Note that html forms are often POST-ed in the HTTP request body in the same format as query strings (with an encoding called application/x-www-form-urlencoded) so this package can be used for that as well.

Quick Intro

The go standard library can convert only between the (query) string and the standard url.Values data type (which is a map[string][]string). This qs package adds struct marshaling and unmarshaling to your arsenal:

                  +--------------+
+---------------->| query string +------------------+
|                 +---------+----+                  |
|                      ^    |                       |
|    url.Values.Encode |    | url.ParseQuery        |
|                      |    v                       |
|                 +----+---------+                  |
|                 |  url.Values  |                  |
|                 +---------+----+                  |
|                      ^    |                       |
|     qs.MarshalValues |    | qs.UnmarshalValues    |
|                      |    v                       |
|                 +----+---------+                  |
+-----------------+    struct    |<-----------------+
    qs.Marshal    +--------------+    qs.Unmarshal

Example:

package main

import "fmt"
import "github.com/pasztorpisti/qs"

type Query struct {
	Search     string
	Page       int
	PageSize   int
	Categories []string `qs:"category"`
}

func main() {
	queryStr, err := qs.Marshal(&Query{
		Search:     "my search",
		Page:       2,
		PageSize:   50,
		Categories: []string{"c1", "c2"},
	})
	fmt.Println("Marshal-Result:", queryStr, err)

	var q Query
	err = qs.Unmarshal(&q, queryStr)
	fmt.Println("Unmarshal-Result:", q, err)

	// Output:
	// Marshal-Result: category=c1&category=c2&page=2&page_size=50&search=my+search <nil>
	// Unmarshal-Result: {my search 2 50 [c1 c2]} <nil>
}

Features

Detailed Documentation

The godoc of the qs package contains more detailed documentation with working examples.