parameters

package module
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2023 License: GPL-3.0 Imports: 21 Imported by: 1

README

go-parameters

Parameter multi-tool that parses json, msg pack, or multipart form data into a parameter object.

Release Build Status Report codecov Go Sponsor Donate


Table of Contents


Installation

go-parameters requires a supported release of Go.

go get -u github.com/mrz1836/go-parameters

Documentation

View the generated documentation

GoDoc

Features
  • Uses the fastest router: Julien Schmidt's httprouter
  • Works with json, msgpack, and multi-part forms
  • Handles all standard types for GetParams
  • Handler methods like MakeParsedReq() for httprouter use
  • Imbue and Permit helper methods
  • GetParams() parses parameters only once
Package Dependencies
Library Deployment

goreleaser for easy binary or library deployment to GitHub and can be installed via: brew install goreleaser.

The .goreleaser.yml file is used to configure goreleaser.

Use make release-snap to create a snapshot version of the release, and finally make release to ship to production.

Makefile Commands

View all makefile commands

make help

List of all current commands:

all                  Runs multiple commands
clean                Remove previous builds and any test cache data
clean-mods           Remove all the Go mod cache
coverage             Shows the test coverage
godocs               Sync the latest tag with GoDocs
help                 Show this help message
install              Install the application
install-go           Install the application (Using Native Go)
lint                 Run the golangci-lint application (install if not found)
release              Full production release (creates release in Github)
release              Runs common.release then runs godocs
release-snap         Test the full release (build binaries)
release-test         Full production test release (everything except deploy)
replace-version      Replaces the version in HTML/JS (pre-deploy)
run-examples         Runs all the examples
tag                  Generate a new tag and push (tag version=0.0.0)
tag-remove           Remove a tag if found (tag-remove version=0.0.0)
tag-update           Update an existing tag to current commit (tag-update version=0.0.0)
test                 Runs vet, lint and ALL tests
test-ci              Runs all tests via CI (exports coverage)
test-ci-no-race      Runs all tests via CI (no race) (exports coverage)
test-ci-short        Runs unit tests via CI (exports coverage)
test-short           Runs vet, lint and tests (excludes integration tests)
uninstall            Uninstall the application (and remove files)
update-linter        Update the golangci-lint package (macOS only)
vet                  Run the Go vet application

Examples & Tests

All unit tests and examples run via GitHub Actions and uses Go version 1.19.x. View the configuration file.

Run all tests (including integration tests)

make test

Run tests (excluding integration tests)

make test-short

Benchmarks

Run the Go benchmarks:

make bench

Code Standards

Read more about this Go project's code standards.


Usage

View the examples

Basic implementation:

package main

import (
    "fmt"
	"log"
	"net/http"

	"github.com/julienschmidt/httprouter"
	"github.com/mrz1836/go-parameters"
)

func Hello(w http.ResponseWriter, req *http.Request) {

	params := parameters.GetParams(req)

	name, _ := params.GetStringOk("name")

	_, _ = fmt.Fprintf(w, `{"hello":"%s"}`, name)
}

func main() {
    router := httprouter.New()
	router.GET("/hello/:name", parameters.GeneralJSONResponse(Hello))
	log.Fatal(http.ListenAndServe(":8080", router))
}

Maintainers

MrZ kayleg
MrZ kayleg

Contributing

View the contributing guidelines and please follow the code of conduct.

How can I help?

All kinds of contributions are welcome 🙌! The most basic way to show your support is to star 🌟 the project, or to raise issues 💬. You can also support this project by becoming a sponsor on GitHub 👏 or by making a bitcoin donation to ensure this journey continues indefinitely! 🚀


License

License

Documentation

Overview

Package parameters parses json, msg pack, or multi-part form data into a parameters object

Index

Examples

Constants

View Source
const (
	// ParamsKeyName standard key name for parameter data
	ParamsKeyName paramKey = "params"

	// DateOnly is only the date
	DateOnly = "2006-01-02"

	// DateTime is not recommended, rather use time.RFC3339
	DateTime = "2006-01-02 15:04:05"

	// HTMLDateTimeLocal is the format used by the input type datetime-local
	HTMLDateTimeLocal = "2006-01-02T15:04"
)

Constants for parameters package

Variables

View Source
var FilteredKeys []string

FilteredKeys is a lower case array of keys to filter when logging

View Source
var KnownAbbreviations = []string{"id", "json", "html", "xml"}

KnownAbbreviations contains lower case versions of abbreviations to match. Any entry in this list will become full upper case when converting from snake_case to camelCase

user_id -> UserID

Functions

func CORSHeaders

func CORSHeaders(fn http.HandlerFunc) httprouter.Handle

CORSHeaders adds cross origin resource sharing headers to a response

func CamelToSnakeCase

func CamelToSnakeCase(str string) string

CamelToSnakeCase converts CamelCase to snake_case Consecutive capital letters will be treated as one word:

HTML -> html

func EnableGZIP

func EnableGZIP(fn httprouter.Handle) httprouter.Handle

EnableGZIP will attempt to compress the response if the client has passed a header value for Accept-Encoding which allows gzip

func GeneralJSONResponse

func GeneralJSONResponse(fn http.HandlerFunc) httprouter.Handle

GeneralJSONResponse calls the default wrappers for a json response: EnableGZIP, JSONResp, MakeHTTPRouterParsedReq, CORSHeaders

func GeneralResponse

func GeneralResponse(fn http.HandlerFunc) httprouter.Handle

GeneralResponse calls the default wrappers: EnableGZIP, MakeHTTPRouterParsedReq, CORSHeaders

func JSONResp

func JSONResp(fn httprouter.Handle) httprouter.Handle

JSONResp will set the content-type to application/json

func MakeFirstUpperCase

func MakeFirstUpperCase(s string) string

MakeFirstUpperCase upper cases the first letter of the string

func MakeHTTPRouterParsedReq

func MakeHTTPRouterParsedReq(fn httprouter.Handle) httprouter.Handle

MakeHTTPRouterParsedReq make http router parsed request

func MakeParsedReq

func MakeParsedReq(fn http.HandlerFunc) http.HandlerFunc

MakeParsedReq make parsed request

func SendCORS

func SendCORS(w http.ResponseWriter, req *http.Request)

SendCORS sends a cross origin resource sharing header only

func SnakeToCamelCase

func SnakeToCamelCase(str string, ucFirst bool) string

SnakeToCamelCase converts snake_case to CamelCase. When:

ucFirst = false - snake_case -> snakeCase
ucFirst = true  - snake_case -> SnakeCase

func UniqueUint64

func UniqueUint64(in []uint64) []uint64

UniqueUint64 removes duplicates from uint64 arrays

Example

ExampleUniqueUint64 shows an example using the method

one := []uint64{3, 2, 1, 3, 3, 3, 3}
unique := UniqueUint64(one)

fmt.Println(unique)
Output:

[3 2 1]

Types

type CustomTypeHandler

type CustomTypeHandler func(field *reflect.Value, value interface{}) error

CustomTypeHandler custom type handler

var CustomTypeSetter CustomTypeHandler

CustomTypeSetter is used when Imbue is called on an object to handle unknown types

type Params

type Params struct {
	Values map[string]interface{}
	// contains filtered or unexported fields
}

Params is the parameter values

func FilterMap added in v0.0.4

func FilterMap(params *Params) *Params

FilterMap will filter the parameters and not log parameters with sensitive data. To add more parameters - see the if in the loop

func GetParams

func GetParams(req *http.Request) *Params

GetParams get parameters

func ParseParams

func ParseParams(req *http.Request) *Params

ParseParams parse parameters

func (*Params) Clone

func (p *Params) Clone() *Params

Clone makes a copy of this params object

func (*Params) Get

func (p *Params) Get(key string) (val interface{}, ok bool)

Get the param by key, return interface

func (*Params) GetBool

func (p *Params) GetBool(key string) bool

GetBool get param by key, return boolean

func (*Params) GetBoolOk

func (p *Params) GetBoolOk(key string) (bool, bool)

GetBoolOk get param by key, return boolean

func (*Params) GetBytes

func (p *Params) GetBytes(key string) []byte

GetBytes get param by key, return slice of bytes

func (*Params) GetBytesOk

func (p *Params) GetBytesOk(key string) ([]byte, bool)

GetBytesOk get param by key, return slice of bytes

func (*Params) GetFileOk

func (p *Params) GetFileOk(key string) (*multipart.FileHeader, bool)

GetFileOk get param by key, return file

func (*Params) GetFloat

func (p *Params) GetFloat(key string) float64

GetFloat get param by key, return float

func (*Params) GetFloatOk

func (p *Params) GetFloatOk(key string) (float64, bool)

GetFloatOk get param by key, return float

func (*Params) GetFloatSlice

func (p *Params) GetFloatSlice(key string) []float64

GetFloatSlice get param by key, return slice of floats

func (*Params) GetFloatSliceOk

func (p *Params) GetFloatSliceOk(key string) ([]float64, bool)

GetFloatSliceOk get param by key, return slice of floats

func (*Params) GetInt

func (p *Params) GetInt(key string) int

GetInt get param by key, return integer

func (*Params) GetInt16

func (p *Params) GetInt16(key string) int16

GetInt16 get param by key, return integer

func (*Params) GetInt16Ok

func (p *Params) GetInt16Ok(key string) (int16, bool)

GetInt16Ok get param by key, return integer

func (*Params) GetInt32

func (p *Params) GetInt32(key string) int32

GetInt32 get param by key, return integer

func (*Params) GetInt32Ok

func (p *Params) GetInt32Ok(key string) (int32, bool)

GetInt32Ok get param by key, return integer

func (*Params) GetInt64

func (p *Params) GetInt64(key string) int64

GetInt64 get param by key, return integer

func (*Params) GetInt64Ok

func (p *Params) GetInt64Ok(key string) (int64, bool)

GetInt64Ok get param by key, return integer

func (*Params) GetInt8

func (p *Params) GetInt8(key string) int8

GetInt8 get param by key, return integer

func (*Params) GetInt8Ok

func (p *Params) GetInt8Ok(key string) (int8, bool)

GetInt8Ok get param by key, return integer

func (*Params) GetIntOk

func (p *Params) GetIntOk(key string) (int, bool)

GetIntOk get param by key, return integer

func (*Params) GetIntSlice

func (p *Params) GetIntSlice(key string) []int

GetIntSlice get param by key, return slice of integers

func (*Params) GetIntSliceOk

func (p *Params) GetIntSliceOk(key string) ([]int, bool)

GetIntSliceOk get param by key, return slice of integers

func (*Params) GetJSON

func (p *Params) GetJSON(key string) map[string]interface{}

GetJSON get param by key, return map of string interface

func (*Params) GetJSONOk

func (p *Params) GetJSONOk(key string) (map[string]interface{}, bool)

GetJSONOk get param by key, return map of string interface

func (*Params) GetString

func (p *Params) GetString(key string) string

GetString get param by key, return string

func (*Params) GetStringOk

func (p *Params) GetStringOk(key string) (string, bool)

GetStringOk get param by key, return string

func (*Params) GetStringSlice

func (p *Params) GetStringSlice(key string) []string

GetStringSlice get param by key, return slice of strings

func (*Params) GetStringSliceOk

func (p *Params) GetStringSliceOk(key string) ([]string, bool)

GetStringSliceOk get param by key, return slice of strings

func (*Params) GetTime

func (p *Params) GetTime(key string) time.Time

GetTime get param by key, return time

func (*Params) GetTimeInLocation

func (p *Params) GetTimeInLocation(key string, loc *time.Location) time.Time

GetTimeInLocation get param by key, return time

func (*Params) GetTimeInLocationOk

func (p *Params) GetTimeInLocationOk(key string, loc *time.Location) (time.Time, bool)

GetTimeInLocationOk get param by key, return time

func (*Params) GetTimeOk

func (p *Params) GetTimeOk(key string) (time.Time, bool)

GetTimeOk get param by key, return time

func (*Params) GetUint64

func (p *Params) GetUint64(key string) uint64

GetUint64 get param by key, return unsigned integer

func (*Params) GetUint64Ok

func (p *Params) GetUint64Ok(key string) (uint64, bool)

GetUint64Ok get param by key, return unsigned integer

func (*Params) GetUint64Slice

func (p *Params) GetUint64Slice(key string) []uint64

GetUint64Slice get param by key, return slice of unsigned integers

func (*Params) GetUint64SliceOk

func (p *Params) GetUint64SliceOk(key string) ([]uint64, bool)

GetUint64SliceOk get param by key, return slice of unsigned integers

func (*Params) HasAll

func (p *Params) HasAll(keys ...string) (bool, []string)

HasAll will return if all specified keys are found in the params object

func (*Params) Imbue

func (p *Params) Imbue(obj interface{})

Imbue sets the parameters to the object by type; does not handle nested parameters

func (*Params) Permit

func (p *Params) Permit(allowedKeys []string)

Permit permits only the allowed fields given by allowedKeys

Directories

Path Synopsis
Package main is an example package showing the use of the parameters package
Package main is an example package showing the use of the parameters package

Jump to

Keyboard shortcuts

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