tiny-url-ex/service/shortener/model.go

72 lines
1.3 KiB
Go

package shortener
import (
"errors"
)
// Model represents an actual tiny url entry in the database.
type Model struct {
tiny string
long string
}
// storage contains entries
var storage []*Model = make([]*Model, 0)
// NewModel builds a tiny model from arguments
func NewModel(tiny string, long string) *Model {
return &Model{
tiny: tiny,
long: long,
}
}
// Search for model in storage
func (mod *Model) Search() error {
for _, row := range storage {
if row.tiny == mod.tiny {
mod.tiny = row.tiny
mod.long = row.long
return nil
}
}
return errors.New("not found")
}
// Create the model in storage
func (mod *Model) Create() error {
// fail if already exists
if mod.Search() == nil {
return errors.New("already exists")
}
storage = append(storage, mod)
return nil
}
// Update the model in storage
func (mod *Model) Update() error {
for _, row := range storage {
if row.tiny == mod.tiny {
row.tiny = mod.tiny
row.long = mod.long
return nil
}
}
return errors.New("not found")
}
// Delete the model from storage
func (mod *Model) Delete() error {
for i, row := range storage {
if row.tiny == mod.tiny && row.long == mod.long {
storage = append(storage[:i], storage[i+1:]...)
return nil
}
}
return errors.New("not found")
}