Skip to content

Instantly share code, notes, and snippets.

View madflojo's full-sized avatar
:octocat:
Writing code that might be useful

Benjamin Cane madflojo

:octocat:
Writing code that might be useful
View GitHub Profile
@madflojo
madflojo / typeassertion.go
Created November 26, 2020 18:58
maps.vs.struct.typeassert
// Print out one of our JSON values
n, ok := data["name"]
if !ok {
// access it another way
n = "default"
}
v, ok := n.(string)
if !ok {
// figure out type another way
v = "default"
@madflojo
madflojo / safejsonmap.go
Last active November 27, 2020 00:29
map.vs.struct.safeparser
package main
import (
"encoding/json"
"fmt"
)
func main() {
// Create a map to parse the JSON
var data map[string]interface{}
@madflojo
madflojo / safeinterfacearray.go
Created November 26, 2020 21:47
maps.vs.struct.interfacearray
// Print out the JSON Numbers
var nums []int
i, ok := data["numbers"].([]interface{})
if ok {
for _, v := range i {
x, ok := v.(float64)
if !ok {
// set to default
nums = []int{}
break
@madflojo
madflojo / structparser.go
Created November 27, 2020 00:37
maps.vs.structs.structparser
package main
import (
"encoding/json"
"fmt"
)
// Example is our main data structure used for JSON parsing
type Example struct {
Name string `json:"name"`
@madflojo
madflojo / structs.go
Created December 6, 2020 17:48
maps.vs.structs.structs
// Example is our main data structure used for JSON parsing
type Example struct {
Name string `json:"name"`
Numbers []int `json:"numbers"`
Nested Nested `json:"nested"`
}
// Nested is an embedded structure within Example
type Nested struct {
IsIt bool `json:"isit"`
@madflojo
madflojo / datastructs.go
Created December 6, 2020 18:07
maps.vs.structs.datastructs
// Print the name
fmt.Printf("Name is %s\n", data.Name)
// Print the Numbers
fmt.Printf("Numbers include")
for _, v := range data.Numbers {
fmt.Printf(" %d", v)
}
fmt.Printf("\n")
@madflojo
madflojo / app.go
Created December 28, 2020 08:38
Example Golang app package structure
package app
import (
"fmt"
)
var ErrShutdown = fmt.Errorf("application was shutdown gracefully")
func Start(...) error {
// Application runtime code goes here
@madflojo
madflojo / main-example.go
Last active December 29, 2020 07:51
Example of a command-line projects main() function.
// main runs the command-line parsing and validations. This function will also start the application logic execution.
func main() {
// Parse command-line arguments
var opts options
args, err := flags.ParseArgs(&opts, os.Args[1:])
if err != nil {
os.Exit(1)
}
// Convert to internal config
@madflojo
madflojo / go-get.sh
Created December 28, 2020 18:29
Go get command example
$ go get -u github.com/madflojo/efs2
@madflojo
madflojo / go-get-cmd.sh
Created December 28, 2020 18:30
Another Go Get example
$ go get -u github.com/madflojo/efs2/cmd/efs2