Go module for encoding structs into URL query parameters

Overview

qs

Build Codecov GoReportCard Release PkgGoDev MIT License

Package sonh/qs encodes structs into url.Values.

Installation

go get github.com/sonh/qs

Usage

import (
    "github.com/sonh/qs"
)

Package qs exports NewEncoder() function to create an encoder.

Encoder caches struct info to speed up encoding process, use a single instance is highly recommended.

Use WithTagAlias() func to register custom tag alias (default is qs)

encoder = qs.NewEncoder(
    qs.WithTagAlias("myTag"),
)

Encoder has Values() and Encode() functions to encode structs into url.Values.

Supported data types:

  • all basic types (bool, uint, string, float64,...)
  • struct
  • slice, array
  • pointer
  • time.Time
  • custom type

Example

type Query struct {
    Tags   []string  `qs:"tags"`
    Limit  int       `qs:"limit"`
    From   time.Time `qs:"from"`
    Active bool      `qs:"active,omitempty"`  //omit empty value
    Ignore float64   `qs:"-"`                 //ignore
}

query := &Query{
    Tags:   []string{"docker", "golang", "reactjs"},
    Limit:  24,
    From:   time.Unix(1580601600, 0).UTC(),
    Ignore: 0,
}

encoder := qs.NewEncoder()
values, err := encoder.Values(query)
if err != nil {
    // Handle error
}
fmt.Println(values.Encode()) //(unescaped) output: "from=2020-02-02T00:00:00Z&limit=24&tags=docker&tags=golang&tags=reactjs"

Bool format

Use int option to encode bool to integer

type Query struct {
    DefaultFmt bool `qs:"default_fmt"`
    IntFmt     bool `qs:"int_fmt,int"`
}

query := &Query{
    DefaultFmt: true, 
    IntFmt:     true,
}
values, _ := encoder.Values(query)
fmt.Println(values.Encode()) // (unescaped) output: "default_fmt=true&int_fmt=1"

Time format

By default, package encodes time.Time values as RFC3339 format.

Including the "second" or "millis" option to signal that the field should be encoded as second or millisecond.

type Query struct {
    Default time.Time   `qs:"default_fmt"`
    Second  time.Time   `qs:"second_fmt,second"` //use `second` option
    Millis  time.Time   `qs:"millis_fmt,millis"` //use `millis` option
}

t := time.Unix(1580601600, 0).UTC()
query := &Query{
    Default: t,
    Second:  t,
    Millis:  t,
}

encoder := qs.NewEncoder()
values, _ := encoder.Values(query)
fmt.Println(values.Encode()) // (unescaped) output: "default_fmt=2020-02-02T00:00:00Z&millis_fmt=1580601600000&second_fmt=1580601600"

Slice/Array Format

Slice and Array default to encoding into multiple URL values of the same value name.

type Query struct {
    Tags []string `qs:"tags"`
}

values, _ := encoder.Values(&Query{Tags: []string{"foo","bar"}})
fmt.Println(values.Encode()) //(unescaped) output: "tags=foo&tags=bar"

Including the comma option to signal that the field should be encoded as a single comma-delimited value.

type Query struct {
    Tags []string `qs:"tags,comma"`
}

values, _ := encoder.Values(&Query{Tags: []string{"foo","bar"}})
fmt.Println(values.Encode()) //(unescaped) output: "tags=foo,bar"

Including the bracket option to signal that the multiple URL values should have "[]" appended to the value name.

type Query struct {
    Tags []string `qs:"tags,bracket"`
}

values, _ := encoder.Values(&Query{Tags: []string{"foo","bar"}})
fmt.Println(values.Encode()) //(unescaped) output: "tags[]=foo&tags[]=bar"

The index option will append an index number with brackets to value name.

type Query struct {
    Tags []string `qs:"tags,index"`
}

values, _ := encoder.Values(&Query{Tags: []string{"foo","bar"}})
fmt.Println(values.Encode()) //(unescaped) output: "tags[0]=foo&tags[1]=bar"

Nested structs

All nested structs are encoded including the parent value name with brackets for scoping.

type User struct {
    Verified bool      `qs:"verified"`
    From     time.Time `qs:"from,millis"`
}

type Query struct {
    User User `qs:"user"`
}

query := Query{
    User: User{
        Verified: true,
        From: time.Now(),
    },
}
values, _ := encoder.Values(query)
fmt.Println(values.Encode()) //(unescaped) output: "user[from]=1601623397728&user[verified]=true"

Custom Type

Implement EncodeParam to encode itself into query param.

Implement IsZero to check whether an object is zero to determine whether it should be omitted when encoding.

type NullableName struct {
	First string
	Last  string
}

func (n NullableName) EncodeParam() (string, error) {
	return n.First + n.Last, nil
}

func (n NullableName) IsZero() bool {
	return n.First == "" && n.Last == ""
}

type Struct struct {
    User  NullableName `qs:"user"`
    Admin NullableName `qs:"admin,omitempty"`
}

s := Struct{
    User: NullableName{
        First: "son",
        Last:  "huynh",
    },
}
encoder := qs.NewEncoder()

values, err := encoder.Values(&s)
if err != nil {
    // Handle error
    fmt.Println("failed")
    return
}
fmt.Println(values.Encode()) //(unescaped) output: "user=sonhuynh"

Limitation

  • if elements in slice/array are struct data type, multi-level nesting are limited
  • no decoder yet

Will improve in future versions

License

Distributed under MIT License, please see license file in code for more details.

You might also like...
Scope function for GORM queries provides easy filtering with query parameters

Gin GORM filter Scope function for GORM queries provides easy filtering with query parameters Usage go get github.com/ActiveChooN/gin-gorm-filter Mod

K8s-go-structs - All k8s API Go structs

k8s-api go types Why? Its nice to have it all in a single package. . |-- pkg |

High-Performance Shortlink ( Short URL ) app creator in Golang. For privacy reasons, you may prefer to host your own short URL app and this is the one to use.
High-Performance Shortlink ( Short URL ) app creator in Golang. For privacy reasons, you may prefer to host your own short URL app and this is the one to use.

About The Project Shortlink App in Golang Multiple Node based Architecture to create and scale at ease Highly performant key-value storage system Cent

Go-based search engine URL collector , support Google, Bing, can be based on Google syntax batch collection URL
Go-based search engine URL collector , support Google, Bing, can be based on Google syntax batch collection URL

Go-based search engine URL collector , support Google, Bing, can be based on Google syntax batch collection URL

A productivity tools to diagnose list of exported URL status from Google Search Console, Analytics, Sitemap URL...etc.

google-url-checker A productivity tools to diagnose list of exported URL status from Google Search Console, Analytics, Sitemap URL...etc. A quick way

Putty-url-scheme - Open PuTTY as a url scheme

PuTTY URL Scheme Helper Open PuTTY as a url scheme Install download release bina

Test-app-url-shortner - A sample url shortener app to test Keploy integration capabilities
Test-app-url-shortner - A sample url shortener app to test Keploy integration capabilities

test-app-url-shortner A sample url shortener app to test Keploy integration capa

Go library for encoding native Go structures into generic map values.

wstructs origin: github.com/things-go/structs Go library for encoding native Go structures into generic map values. Installation Use go get. go ge

Use SQL to instantly query file, domain, URL and IP scanning results from VirusTotal.
Use SQL to instantly query file, domain, URL and IP scanning results from VirusTotal.

VirusTotal Plugin for Steampipe Use SQL to query file, domain, URL and IP scanning results from VirusTotal. Get started → Documentation: Table definit

Library for scanning data from a database into Go structs and more

scany Overview Go favors simplicity, and it's pretty common to work with a database via driver directly without any ORM. It provides great control and

GoLobby DotEnv is a lightweight package for loading dot env (.env) files into structs for Go projects

DotEnv GoLobby DotEnv is a lightweight package for loading dot env (.env) files into structs for Go projects Documentation Supported Versions It requi

Converts a database into gorm structs and RESTful api

gen The gen tool produces a CRUD (Create, read, update and delete) REST api project template from a given database. The gen tool will connect to the d

Allows parsing CSV files into custom structs and implements required fields that can't be empty

Welcome to Go Custom CSV Parser 👋 Allows parsing CSV files into custom structs and implements required fields that can't be empty 🏠 Homepage Install

Envopts - Provides a code generator for turning env structs into functional options

envopts Provides a code generator to turn structs annotated for the popular env

A fast, easy-of-use and dependency free custom mapping from .csv data into Golang structs

csvparser This package provides a fast and easy-of-use custom mapping from .csv data into Golang structs. Index Pre-requisites Installation Examples C

Go-Postgresql-Query-Builder - A query builder for Postgresql in Go

Postgresql Query Builder for Go This query builder aims to make complex queries

`go-redash-query` is a simple library to get structed data from `redash query` sources

go-redash-query go-redash-query is a simple library to get structed data from redash query sources Example Source table id name email 1 Dannyhann rhrn

whois-go is a simple Go module for domain and ip whois info query

whois-go is a simple Go module for domain and ip whois info query

PHP functions implementation to Golang. This package is for the Go beginners who have developed PHP code before. You can use PHP like functions in your app, module etc. when you add this module to your project.

PHP Functions for Golang - phpfuncs PHP functions implementation to Golang. This package is for the Go beginners who have developed PHP code before. Y

Comments
  • Panic when encoding empty slice with

    Panic when encoding empty slice with "comma" tag.

    Running this code results in panic:

    package main
    
    import (
    	"fmt"
    
    	"github.com/sonh/qs"
    )
    
    type Query struct {
    	Tags []string `qs:"tags,comma"`
    }
    
    func main() {
    	encoder := qs.NewEncoder()
    
    	values, _ := encoder.Values(&Query{Tags: []string{}})
    	fmt.Println(values.Encode())
    }
    
    

    Output

    panic: runtime error: index out of range [0] with length 0
    
    goroutine 1 [running]:
    github.com/sonh/qs.(*listField).formatFnc(0xc00007c080, {0x4a5140?, 0xc000010048?, 0xc000014280?}, 0xc000014290)
            /home/pnx/go/pkg/mod/github.com/sonh/[email protected]/encode_field.go:116 +0x2f5
    github.com/sonh/qs.(*encoder).encodeStruct(0xc00009c040, {0x4ab780?, 0xc000010048?, 0x40c7e7?}, 0xc0000921b0, {0x0, 0x0, 0x0})
            /home/pnx/go/pkg/mod/github.com/sonh/[email protected]/encode.go:190 +0x391
    github.com/sonh/qs.(*Encoder).Values(0xc00007c020, {0x4a3400?, 0xc000010048?})
            /home/pnx/go/pkg/mod/github.com/sonh/[email protected]/encode.go:94 +0x1f4
    main.main()
            /home/pnx/code/qs/test.go:16 +0x54
    exit status 2
    

    Correct behavior would be to encode the list into a empty string.

    bug good first issue 
    opened by pnx 3
Releases(v0.6.2)
Owner
Son Huynh
Gopher, Android Developer
Son Huynh
A Form Encoding & Decoding Package for Go

form A Form Encoding & Decoding Package for Go, written by Alvaro J. Genial. Synopsis This library is designed to allow seamless, high-fidelity encodi

Alvaro J. Genial 228 Nov 23, 2022
a package for decode form's values into struct in Go

formam A Go package to decode HTTP form and query parameters. The only requirement is Go 1.10 or later. Features Infinite nesting for maps, structs an

Monoculum 177 Nov 25, 2022
go-querystring is Go library for encoding structs into URL query strings.

go-querystring go-querystring is a Go library for encoding structs into URL query parameters. Usage import "github.com/google/go-querystring/query" go

Google 1.6k Jan 9, 2023
Tag based url Query parameters Constructor.

taqc ?? Tag based url Query parameters Constructor. (This is pronounced as same as "taxi") Synopsis type Query struct { Foo string `ta

moznion 2 Jan 11, 2022
:steam_locomotive: Decodes url.Values into Go value(s) and Encodes Go value(s) into url.Values. Dual Array and Full map support.

Package form Package form Decodes url.Values into Go value(s) and Encodes Go value(s) into url.Values. It has the following features: Supports map of

Go Playgound 573 Dec 26, 2022
gup aka Get All Urls parameters to create wordlists for brute forcing parameters.

Description GUP is a tool to create wrodlists from the urls. Purpose The purpose of this tool is to create wordlists for brute forcing parameters. Ins

Chan Nyein Wai 14 Feb 25, 2022
Go structure annotations that supports encoding and decoding; similar to C-style bitfields. Supports bitfield packing, self-describing layout parameters, and alignment.

STRUCTure EXtensions structex provides annotation rules that extend Go structures for implementation of encoding and decoding of byte backed data fram

Hewlett Packard Enterprise 54 Oct 13, 2022
Utility package that provides the ability to more conveniently work with URL parameters.

Utility package that provides the ability to more conveniently work with URL parameters.

Radik Khisamutdinov 1 Feb 8, 2022
go-eexcel implements encoding and decoding of XLSX like encoding/json

go-eexcel go-eexcel implements encoding and decoding of XLSX like encoding/json Usage func ExampleMarshal() { type st struct { Name string `eexce

sago35 0 Dec 9, 2021
A codec for Go structs with support for chainable encoding/decoding hooks.

structool A codec for Go structs with support for chainable encoding/decoding hooks. Features Provide a uniform codec by combining mapstructure and st

Luo Peng 11 Jan 15, 2022