common

package module
v5.2.0 Latest Latest
Warning

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

Go to latest
Published: Aug 12, 2023 License: MPL-2.0 Imports: 18 Imported by: 1

README

Common

Test Go Golanglint CI DeepSource Go Report Card codecov

This repo contains common code that I use between my programs. There are currently some tests and at some point I might get around to writing more.

Tested with go versions 1.18, 1.19, and 1.20.

Benchmark

Benchmarks are taken from latest-ubuntu and go version 1.20.

BenchmarkJSONResponse-2           	 1480198	       874.1 ns/op	    1024 B/op	      10 allocs/op
BenchmarkWOAllowedMethod-2        	 1455447	       809.3 ns/op	    1016 B/op	      10 allocs/op
BenchmarkAllowedMethods-2         	 1000000	      1165 ns/op	    1088 B/op	      13 allocs/op
BenchmarkDeniedAllowedMethods-2   	  808725	      1269 ns/op	    1128 B/op	      14 allocs/op
BenchmarkContentResponse-2        	 1508470	       799.8 ns/op	    1013 B/op	      10 allocs/op
BenchmarkStringResponse-2         	 1480393	       816.2 ns/op	    1016 B/op	      10 allocs/op
BenchmarkJSONMarshall-2           	 1205497	      1002 ns/op	    1024 B/op	      10 allocs/op
BenchmarkGenerate-2               	  804207	      1457 ns/op
BenchmarkJSONParse-2              	  694284	      1871 ns/op	      80 B/op	       2 allocs/op
BenchmarkYAMLParse-2              	  619479	      1844 ns/op	      80 B/op	       2 allocs/op
BenchmarkStringSearch2-2          	14119131	        83.43 ns/op
BenchmarkStringSearch10-2         	 7538738	       160.3 ns/op
BenchmarkFloatSearch2-2           	17752921	        65.32 ns/op
BenchmarkFloatSearch10-2          	10868433	       109.4 ns/op
BenchmarkIntSearch2-2             	17698303	        65.83 ns/op
BenchmarkIntSearch10-2            	11625736	       103.5 ns/op
BenchmarkGetEnv-2                 	31068798	        38.51 ns/op	       0 B/op	       0 allocs/op
BenchmarkGetEnvMissing-2          	32717121	        36.52 ns/op
BenchmarkSHA256-2                 	   54486	     21549 ns/op
BenchmarkSHA384-2                 	   56664	     21297 ns/op
BenchmarkSHA512-2                 	   55195	     21276 ns/op
BenchmarkSkipRoot-2               	  789014	      1295 ns/op
BenchmarkEnvironMap-2             	   45550	     28015 ns/op
BenchmarkFileExists-2             	  951858	      1225 ns/op
BenchmarkFileExistsMissing-2      	  972051	      1159 ns/op

Documentation

Index

Constants

View Source
const JSONApplicationType = "application/json; charset=utf-8"

JSONApplicationType is MIME type for JSON data.

Variables

This section is empty.

Functions

func AllowedMethods

func AllowedMethods(handler http.HandlerFunc, methods string) http.HandlerFunc

AllowedMethods is a decorator to only allow comma separated methods.

func ContentResponse

func ContentResponse(w http.ResponseWriter, contentType string, response []byte)

ContentResponse writes a http response with a given content type.

func DoJSONRequest

func DoJSONRequest(method, url string, requestBody, responseBody interface{}) (*http.Response, error)

DoJSONRequest sends a client JSON request. The responseBody should be a pointer to the address of a struct. If a blank string is passed then it will default to a POST request. Example:

var response exampleStruct

resp, err := DoJSONRequest("POST", "http://example.com", nil, &response)

or

response := new(exampleStruct)

resp, err := DoJSONRequest("POST", "http://example.com", nil, response).

func DownloadFile

func DownloadFile(url, filename string) (ok bool, err error)

DownloadFile downloads a file and writes it to the file path. Overwrites any file at the path.

func EnvironMap

func EnvironMap() map[string]string

EnvironMap returns a string map of environment variables.

func FileExists

func FileExists(filename string) bool

FileExists is a function to check if the file exists at the path.

func FloatSearch

func FloatSearch(target float64, array []float64) bool

FloatSearch checks an array of float64 to see if the target float is in it.

func GenerateRandInt

func GenerateRandInt(max int) (returnValue int, returnError error)

GenerateRandInt securely generate a random int64. The input is the maximum value that the random int can be.

func GetDefaultFromEnv added in v5.2.0

func GetDefaultFromEnv(key, fallback string) string

GetDefaultFromEnv checks if the key exists in the environment variables. If yes then returns that value and if not returns default value.

func GetEnv

func GetEnv(key, fallback string) string

GetEnv checks if the key exists in the environment variables. If yes then returns that value and if not returns default value.

func GetEnvSecret

func GetEnvSecret(secretName string) (secret string)

GetEnvSecret will get either an OS environment variable. If there is no environment variable set it will check to see if a variable with _FILE is set. If so then it will read the secret name as a filepath and return the content.

func HashFile

func HashFile(algorithm string, filepath string) (value string, err error)

HashFile generates a string hash of the given file path. Supported hashing algorithm: sha256, sha384, and sha512.

func IntSearch

func IntSearch(target int, array []int) bool

IntSearch checks an array of integers to see if the target int is in it.

func JSONMarshalResponse

func JSONMarshalResponse(w http.ResponseWriter, body interface{})

JSONMarshalResponse writes a http response as JSON. Takes an interface.

func JSONResponse

func JSONResponse(w http.ResponseWriter, response []byte)

JSONResponse writes a http response as JSON. Takes a byte array as input.

func ParseYamlOrJSON

func ParseYamlOrJSON(fileName string, outputInterface interface{}) error

ParseYamlOrJSON will detect if a file is either a JSON or YAML file and marshal it to the provided interface. Yaml files can end in .yml or .yaml

Example:

var response exampleStruct

if err := ParseYamlOrJSON("helloworld.json", &response); err != nil { log.Fatal(err)}

OR

response := new(exampleStruct)

err := ParseYamlOrJSON("helloworld.yml" response); err != nil { log.Fatal(err)}.

func SkipRoot

func SkipRoot(jsonBlob []byte) (values json.RawMessage)

SkipRoot skips the root struct of a JSON message but will return nil if an error happens. Taken from https://stackoverflow.com/a/20873511.

func SkipRootWithError

func SkipRootWithError(jsonBlob []byte) (json.RawMessage, error)

SkipRootWithError skips the root struct of a JSON message but will return an error. Taken from https://stackoverflow.com/a/20873511.

func StringResponse

func StringResponse(w http.ResponseWriter, response string)

StringResponse writes a http response as a string.

func StringSearch

func StringSearch(target string, array []string) bool

StringSearch checks an array of strings to see if the target string is in it.

Types

This section is empty.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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