// 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)
}
)