whatever

package module
v0.0.0-...-7296a43 Latest Latest
Warning

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

Go to latest
Published: Mar 28, 2015 License: MIT Imports: 6 Imported by: 1

README

whatever

BuildStatus Coverage Status GoDoc status

Package whatever is a Go package that exports type Params with some useful methods on top of map[string]interface{}

Example

NewFromJSON

import (
  "fmt"

  "github.com/ndyakov/whatever"
)

var body = []byte(`
{
  "int": -10,
  "string": "test",
  "time": "2015-02-20T21:22:23.24Z",
  "nestedParams": {
    "arrayStrings": ["one","two","three"],
    "arrayInts": [1,2,3,4],
  }
}
`)

func main() {
  p := whatever.NewFromJSON(body)
  fmt.Println(p.GetInt("int")) // -10
  fmt.Println(p.GetP("nestedParams").GetSliceStrings("arrayStrings")[1]) // two
}
Params{}
func sum(p whatever.Params) int {
  x := p.GetInt("x")
  // or x := p.GetI("x").(int)
  y := p.GetInt("y")
  // or y := p.GetI("y").(int)
  return x + y
}

func main() {
  p := whatever.Params{x: 10, y: 5}
  fmt.Println(sum(p)) // 15
}

Install

Get the package

go get github.com/ndyakov/whatever

Import in your source

import "github.com/ndyakov/whatever"

Introduction

The main idea behind whatever was for the type Params to be used when unmarshaling JSON data from an application/json request, but after adding the Add and Remove methods I think that this Params type can be useful in variety of other cases as well.

There is a method that can transform the Params structure to url.Values structure with specified prefix and suffix, for the result can be used with Gorillas schema or Gojis params packages. Although some of the getters are useful for unmarshaled JSON date you can also Add your own values to the Params structure. You can also access nested Params objects. If you need you can validate the existence of a specific key by using the Required method.

type Params

This may be outdated, please check the godoc for up-to-date documentation

Contributions

Before contributing please execute:

  • gofmt
  • golint
  • govet

License

The MIT License (MIT)

Copyright (c) 2015 Nedyalko Dyakov

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Documentation

Overview

Package whatever holds just one type - Params.

The Params type is map[string]interface{} with some useful methods to it.

This type was initially created to be used as structure in which JSON requests are to be unmarshaled and accessed with ease. Because of this, the Params type have a getter for time.Time that will parse a Date string that follows the RFC3339 format (the Javascript build-in JSON format).

There is a method that can transform the Params structure to url.Values structure with specified prefix and suffix, for the result can be used with Gorilla`s schema or Goji`s params packages.

Although some of the getters are useful for unmarshaled JSON date you can also Add your own values to the Params structure.

You can also access nested Params objects.

If you need you can validate the existence of a specific key by using the Required method.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Params

type Params map[string]interface{}

Params is a type on top of map[string]interface{} that has a few useful getters and other methods. This type can help you to work with JSON data that can be unmarshaled into it and then extracted with the appropriate type (it even has a getter for time.Time). Also the Required and Empty methods may be helpful with validating data. It is possible to work with nested Params, getting an Interface that you can cast yourself to the wanted type and adding new values to the Params structure.

func NewFromJSON

func NewFromJSON(jsonBody []byte) (Params, error)

NewFromJSON receives a slice of bytes that should be json body and returns Params structure for that json body and an error if there was one while decoding the json.

func (Params) Add

func (p Params) Add(key string, value interface{}) bool

Add adds a new pair(key, value) to the Params structure. Returns true if an existing value was overwritten.

func (Params) Defaults

func (p Params) Defaults(set map[string]interface{})

func (Params) Delete

func (p Params) Delete(key string) interface{}

Delete deletes a key from the structure and returns it's value.

This method works only on top-level keys. To delete a nested parameter you may want to you may want to first call GetP to get the nested object.

Example:

v := params.GetP("nested").Delete("key")

It won't fail even if called on a missing key.

func (Params) Empty

func (p Params) Empty() bool

Empty checks if the Params structure is empty. Returns false if a there are elements in the structure.

func (Params) Get

func (p Params) Get(key string) string

Get returns a string representation of the value with the specified key. Returns empty string if there is no value with the provided key.

func (Params) GetFloat

func (p Params) GetFloat(key string) float32

GetFloat parses the value with the provided key to an float32. If there is an error with the parsing, returns 0. This is actually the same as calling GetFloat32.

func (Params) GetFloat32

func (p Params) GetFloat32(key string) float32

GetFloat32 parses the value with the provided key to an float32. If there is an error with the parsing, returns 0.

func (Params) GetFloat64

func (p Params) GetFloat64(key string) float64

GetFloat64 parses the value with the provided key to an float64. If there is an error with the parsing, returns 0.

func (Params) GetI

func (p Params) GetI(key string) interface{}

GetI will return the same as map[key] would have returned. Returns an interface that you can try to cast to other types. If there is no value with that key it will return nil.

func (Params) GetInt

func (p Params) GetInt(key string) int

GetInt parses the value with the provided key to an int. If there is an error with the parsing, returns 0.

func (Params) GetInt64

func (p Params) GetInt64(key string) int64

GetInt64 parses the value with the provided key to an int64. If there is an error with the parsing, returns 0.

func (Params) GetInt8

func (p Params) GetInt8(key string) int8

GetInt8 parses the value with the provided key to an int8. If there is an error with the parsing, returns 0.

func (Params) GetP

func (p Params) GetP(key string) Params

GetP will return Params structure if the value with the specified key is of either map[string]interface{} or Params type. Returns empty Params if the key is missing or if the value was not one of the desired types.

func (Params) GetSlice

func (p Params) GetSlice(key string) []interface{}

GetSlice returns a slice of interface{} if the value with the provided key can be casted to a slice. Otherwise returns nil.

func (Params) GetSliceInts

func (p Params) GetSliceInts(key string) []int

GetSliceInts will return a slice of strings. This slice of strings will be a result of casting the value corresponding to the provided key to a slice of interface{} and then individually casting each element to an int. Only those elements that can be casted to an int will be present in the final result. Those who cannot be casted to int will be silently ignored. If the is not value with that key or the value is not a slice, nil will be returned.

func (Params) GetSliceStrings

func (p Params) GetSliceStrings(key string) []string

GetSliceStrings will return a slice of strings. This slice of strings will be a result of casting the value corresponding to the provided key to a slice of interface{} and then individually casting each element to a string. Only those elements that can be casted to a string will be present in the final result. Those that cannot be casted to string will be silently ignored. If the is not value with that key or the value is not a slice, nil will be returned.

func (Params) GetString

func (p Params) GetString(key string) string

GetString returns a string only if the value with the specified key can be casted to string. Will return an empty string otherwise.

func (Params) GetTime

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

GetTime will return the value with the specified key parsed as time.Time structure. The layout is time.RFC3339 or in other words the JSON format for the Date object in JavaScript. The value should look like this:

"2015-02-27T21:53:57.582Z"

Otherwise returns time.Time{}

func (Params) Keys

func (p Params) Keys() []string

Keys will return the top-level keys of the params. Keep in mind if you need the nested keys as well you can use NestedKeys.

func (Params) Merge

func (p Params) Merge(set map[string]interface{})

Merge merges two params objects (the parameter can be map[string]interface{} as well). All fields from the parameter will be set to the receiver.

Note: This is working only on top-level keys.

func (Params) NestedKeys

func (p Params) NestedKeys() []string

NestedKeys will return all keys in the params map. The nested keys will be prefixed with a dot. Example:

{ "one": { "two": 3 } }

Will result in the following key:

"one.two"

func (Params) Required

func (p Params) Required(keys ...string) error

Required will return an error if one of the passed keys is missing in the Params structure. As far as Required cares - an empty string is the same as missing value. To validate nested parameters please use the dotted notation:

some_key.nested_key.last_key

Returns an error message of the following type:

"the parameter {key} is required"

If all keys are present will return nil.

func (Params) URLValues

func (p Params) URLValues(prefix, suffix string) url.Values

URLValues return the values in the Params structure as url.Values that can be then used with packages as gorilla`s schema or goji`s params. The schema and params packages expects different keys for the nested values. For this to be able to generate the expected keys you may need to pass the prefix and the suffix of the nested key. If the prefix is empty string, then the prefix will be set to dot (".") and the suffix will be an empty string. This is the way that gorilla`s schema expect the nested keys to be represented. Example:

some_key.inner_key.last_key

This somewhat resembles the mongo notation of nested objects as well. To be able to use this with params, you will need to pass an prefix "[" and suffix "]". The key from the previous example will now be:

some_key[inner_key][last_key]

If the Params structure is blank, then an empty url.Values will be returned.

Jump to

Keyboard shortcuts

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