All Projects → sonh → Qs

sonh / Qs

Licence: mit
Go module for encoding structs into URL query parameters

Programming Languages

go
31211 projects - #10 most used programming language

Projects that are alternatives of or similar to Qs

sms
A Go library for encoding and decoding SMSs
Stars: ✭ 37 (-32.73%)
Mutual labels:  encoding, encoder
AnimatedGif
📼 A high performance .NET library for reading and creating animated GIFs
Stars: ✭ 106 (+92.73%)
Mutual labels:  encoding, encoder
gonvert
Golang character encoding converter with an automatic code-estimation.
Stars: ✭ 24 (-56.36%)
Mutual labels:  encoding, encoder
Minih264
Minimalistic H264/SVC encoder single header library
Stars: ✭ 390 (+609.09%)
Mutual labels:  encoding, encoder
ffcvt
ffmpeg convert wrapper tool
Stars: ✭ 32 (-41.82%)
Mutual labels:  encoding, encoder
Form
🚂 Decodes url.Values into Go value(s) and Encodes Go value(s) into url.Values. Dual Array and Full map support.
Stars: ✭ 454 (+725.45%)
Mutual labels:  encoder, form
Country Fns
🌏 Useful country data for forms and stuff.
Stars: ✭ 35 (-36.36%)
Mutual labels:  form
Vue Formular
a comprehensive vue.js form component
Stars: ✭ 45 (-18.18%)
Mutual labels:  form
Ok
✔️ A tiny TypeScript library for form validation
Stars: ✭ 34 (-38.18%)
Mutual labels:  form
Formality
Forms made simple (and cute). Designless, multistep, conversational, secure, all-in-one WordPress forms plugin.
Stars: ✭ 30 (-45.45%)
Mutual labels:  form
Fast ber
A C++11 ASN.1 BER Encoding and Decoding Library
Stars: ✭ 54 (-1.82%)
Mutual labels:  encoding
Insert Text At Cursor
Fast crossbrowser insertion of text at cursor position in a textarea / input
Stars: ✭ 49 (-10.91%)
Mutual labels:  form
Ncform
🍻 ncform, a very nice configuration generation way to develop forms ( vue, json-schema, form, generator )
Stars: ✭ 1,009 (+1734.55%)
Mutual labels:  form
Iocane
An odorless, tasteless NodeJS crypto library that dissolves instantly in liquid
Stars: ✭ 35 (-36.36%)
Mutual labels:  encoding
Mobx React Form
Reactive MobX Form State Management
Stars: ✭ 1,031 (+1774.55%)
Mutual labels:  form
Cryptii
Web app and framework offering modular conversion, encoding and encryption
Stars: ✭ 971 (+1665.45%)
Mutual labels:  encoding
Vue Form Wizard
Vue.js 2 wizard
Stars: ✭ 1,053 (+1814.55%)
Mutual labels:  form
Angular Contenteditable Accessor
This accessor allows you to use Angular forms with contenteditable elements with ease. It has zero dependencies, other than Angular itself as peer and works with Angular 4+ in all modern browsers, including Internet Explorer 11
Stars: ✭ 34 (-38.18%)
Mutual labels:  form
Usetheform
React library for composing declarative forms, manage their state, handling their validation and much more.
Stars: ✭ 40 (-27.27%)
Mutual labels:  form
Vanilla Autokana
A Vanilla-JavaScript library to complete furigana automatically.
Stars: ✭ 48 (-12.73%)
Mutual labels:  form

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.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].