Skip to content

Instantly share code, notes, and snippets.

@jeremija
Created March 6, 2020 07:17
Show Gist options
  • Save jeremija/60f9a393f761dd92f3a41cb2694436df to your computer and use it in GitHub Desktop.
Save jeremija/60f9a393f761dd92f3a41cb2694436df to your computer and use it in GitHub Desktop.
go example
// db/db.go
type MyDB struct {
  DB *sql.DB
}

func Exec(query string, params... interface{}) error {...}
func Select(target interface{}, query string, params... interface) error {...}
// services/userservice.go

type dbSelector interface {
  type Select(target interface{}, query string, params... interface) error
}

type UserService struct {
  db dbSelector
}

func NewUserService(db dbSelector) UserService {
  return UserService{db: db}
}

func (u UserService) UserAdd(username string, password string) (domain.User, error) {
  var user domain.User
  err := u.db.Select(&user, "insert into user (...) values (...) returning *", username, password)
  return user, err
}

func (u UserService) UserGet(username string) (domain.User, error) {
  var user domain.User
  err := u.db.Select(&user, "select * from user where username = $1", username)
  return user, err
}
// handler/user.go

type userAdder interface {
  func UserAdd(username string, password string) (domain.User, error)
}

func NewHandlerAddUser(service userAdder) http.HandlerFunc {
  return func(w http.ResponseWriter, r *http.Request) {
    username := r.PostFormValue("username")
    password := r.PostFormValue("password")
    user, err := service.UserAdd(username, password)
    // TODO handle error
    http.Redirect(w, r, "/users/" + user.ID, 302)
  }
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment