Skip to content

Instantly share code, notes, and snippets.

@percybolmer
Last active August 6, 2021 11:37
Show Gist options
  • Save percybolmer/865c48c7ec0bbb3a232929387ebb2363 to your computer and use it in GitHub Desktop.
Save percybolmer/865c48c7ec0bbb3a232929387ebb2363 to your computer and use it in GitHub Desktop.
package main
import (
"errors"
"log"
)
func main() {
// Create new testDB
database := NewTestDB()
// create the API and apply the memory database to it
api := API{
db: database,
}
// Add User using the API instead
err := api.db.AddUser("findMe", "[email protected]")
if err != nil {
log.Fatal(err)
}
// fetch user will also still work using the interface
user, err := api.db.GetUser("findMe")
if err != nil {
log.Fatal(err)
}
log.Println(user)
}
// UserDatabase is an interface that describes what's expected from structs that should be used as databases
type UserDatabase interface {
GetUser(username string) (*User, error)
AddUser(username, email string) error
}
// API is a struct that will act as an API and connect to a database
type API struct {
db UserDatabase
}
// User is a data representation of our users
type User struct {
Name string
Email string
}
// TestingDatabase is a user database that always returns errors used for testing
type TestingDatabase struct {
Users map[string]*User
}
func NewTestDB() *TestingDatabase {
return &TestingDatabase{
Users: make(map[string]*User),
}
}
// GetUser will print a user or an Error if not found
func (testDB *TestingDatabase) GetUser(username string) (*User, error) {
// Search for User
return nil, errors.New("User does not exist")
}
// AddUser will add a user to the database
func (testDB *TestingDatabase) AddUser(username, email string) error {
return errors.New("User already exists")
}
// MemoryDatabase is a user database that holds users in memory
type MemoryDatabase struct {
Users map[string]*User
}
func NewMemDB() *MemoryDatabase {
return &MemoryDatabase{
Users: make(map[string]*User),
}
}
// GetUser will print a user or an Error if not found
func (memDB *MemoryDatabase) GetUser(username string) (*User, error) {
// Search for User
if user, ok := memDB.Users[username]; ok {
return user, nil
}
return nil, errors.New("User does not exist")
}
// AddUser will add a user to the database
func (memDB *MemoryDatabase) AddUser(username, email string) error {
if _, ok := memDB.Users[username]; ok {
return errors.New("User already exists")
}
memDB.Users[username] = &User{
Name: username,
Email: email,
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment