qs

package module
v0.0.0-...-2bbe0f4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 12, 2015 License: Apache-2.0 Imports: 4 Imported by: 1

README

qs

Package qs encodes structs into URL query strings.

It uses reflection and Go struct tags (like encoding/json package) to identify field names and encoding options.

It's handy when systematically constructing URL query parameters. It only has one function exposed that returns net/url.Values.

Browse documentation on GoDoc: GoDoc

Example


import "github.com/ahmetalpbalkan/qs"
...

type SearchParams struct {
	Query string `qs:"q"` 
	Count int    `qs:"num,omitempty"`
	Start int    `qs:"start,omitempty"`
}

params := SearchParams{
	Query: "apple pie",
	Count: 30}

addr := &url.URL{
	Schema:   "https",
	Host:     "google.com",
	Path:     "search",
	RawQuery: qs.Encode(params).Encode(), // Magic!
}.String()

fmt.Println(addr)
// Output: https://google.com/search?q=apple+pie&num=30

License

This package is distributed under Apache 2.0 License. See LICENSE for more.

Who is using this?

  • [Add your project here]

Authors

Documentation

Overview

Package qs encodes structs into URL query strings.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Encode

func Encode(v interface{}) url.Values

Encode returns the URL query parameters from the given structure v.

It panics if v is not a struct or a struct that contains fields of types other than bool, int, float, string, slice/array of those or another slice with String(). If v is nil, zero value for url.Values is returned.

Literal values are encoded with their Go string representations.

Pointer fields in v are derefenced until they are no longer pointers.

Each field in v struct gets encoded as an URL value, unless:

  • the field's tag is "-", or
  • the field is empty and its tag specifies the "omitempty" option.

Similar to encoding/json package, the default key is the field name but can be specified in the struct field's tag value. The "qs" key in the struct field's tag value is the key name, followed by an optional comma and an optional "omitempty" to discard the key when the value of the field is its zero value.

Example
package main

import (
	"fmt"
	"qs"
)

func main() {
	type QueryParams struct {
		Query string   `qs:"q"`
		Count int      `qs:"num,omitempty"`
		Opt   []string `qs:"opt"`
	}

	p := QueryParams{
		Query: "apple pie",
		Count: 10,
		Opt:   []string{"safe", "localized"},
	}

	fmt.Println(qs.Encode(p).Encode())
}
Output:

num=10&opt=safe&opt=localized&q=apple+pie

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL