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 / copymap.go
Created September 3, 2022 19:17
ThreadSafe Packages - Copy Map
// Directory will return a map of all people stored within the Directory.
func (d *Directory) Directory() map[string]Person {
d.RLock()
defer d.RUnlock()
m := make(map[string]Person)
for k, v := range d.directory {
m[k] = v
}
return m
}
@madflojo
madflojo / diretory-method.go
Created September 3, 2022 19:11
ThreadSafe Packages - Directory Method
// Directory will return a map of all people stored within the Directory.
func (d *Directory) Directory() map[string]Person {
d.RLock()
defer d.RUnlock()
return d.directory
}
@madflojo
madflojo / name.go
Created September 3, 2022 19:03
ThreadSafe Packages - Name
// Name will return the current Directory name.
func (d *Directory) Name() string {
d.RLock()
defer d.RUnlock()
return d.name
}
@madflojo
madflojo / setname.go
Created September 3, 2022 18:51
ThreadSafe Packages - SetName
// SetName will change the name of the current Directory.
func (d *Directory) SetName(n string) error {
if n == "" {
return fmt.Errorf("cannot have an empty name")
}
d.Lock()
defer d.Unlock()
d.name = n
return nil
}
@madflojo
madflojo / directory-struct.go
Created September 3, 2022 18:50
ThreadSafe Packages
// Directory provides the ability to store and lookup people.
type Directory struct {
sync.RWMutex
// directory stores known People
directory map[string]Person
// name is used to identify the Directory instance
name string
}
@madflojo
madflojo / import.go
Created September 3, 2022 18:49
Threadsafe Packages - Import
import (
"fmt"
"sync"
)
@madflojo
madflojo / httphandler.go
Created September 3, 2022 18:47
Threadsafe Packages - HTTP Handler
http.HandleFunc("/count", func(w http.ResponseWriter, r *http.Request) {
counter = counter + 1
})
@madflojo
madflojo / threadsafe.go
Created September 3, 2022 18:15
Threadsafe Packages - final
/*
Package directory is an example package that creates an internal directory for People.
This package is an example used for a Blog article and is not for anything else.
*/
package directory
import (
@madflojo
madflojo / logic.go
Created August 24, 2022 13:38
Threadsafe Packages - Base with Logic but unsafe
/*
Package directory is an example package that creates an internal directory for People.
This package is an example used for a Blog article and is not for anything else.
*/
package directory
import (
@madflojo
madflojo / new-func.go
Created August 21, 2022 23:50
Threadsafe Packages Article: New
// New is used to create a new instance of Directory.
func New(name string) (*Directory, error) {
return &Directory{}, nil
}