Answer the question
In order to leave comments, you need to log in
How to correctly access a database in Go using the structure described below?
the second day I can’t figure out how to code correctly.
Task:
we have a User Structure, login and password from the front come into it.
type User struct {
Username string `json:"username"`
Password string `json:"password"`
}
package ui
import (
"encoding/json"
"fmt"
"net"
_ "github.com/lib/pq"
_ "github.com/go-sql-driver/mysql"
"database/sql"
"github.com/jmoiron/sqlx"
)
type User struct {
Username string `json:"username"`
Password string `json:"password"`
}
type db interface {
SelectUsers() ([]*User, error)
}
type Model struct {
db
}
type myDb struct {
dbConn *sqlx.DB
sqlSelectUsers *sqlx.Stmt
sqlSelectUser *sqlx.Rows
}
func New(db db) *Model {
return &Model{
db: db,
}
}
func (m *Model) Users() ([]*User, error) {
return m.SelectUsers()
}
//****************************************//
//*коннект к бд, все работает ок.*//
//***************************************//
func InitDb(cfg Config) (*myDb, error) {
if dbConn, err := sqlx.Connect("mysql", cfg.ConnectString); err != nil {
return nil, err
} else {
p := &myDb{dbConn: dbConn}
if err := p.dbConn.Ping(); err != nil {
return nil, err
}
if err := p.prepareSqlStatements(); err != nil {
return nil, err
}
return p, nil
}
}
func (p *myDb) prepareSqlStatements() (err error) {
if p.sqlSelectUsers, err = p.dbConn.Preparex(
"SELECT login, pass, id FROM users WHERE login=? AND pass=?",
); err != nil {
return err
}
}
func (p *myDb) SelectUsers() ([]*model.User, error) {
user := make([]*model.User, 0)
if err := p.sqlSelectUsers.Select(&user); err != nil {
return nil, err
}
return user, nil
}
usr, err := m.Users()
js, err := json.Marshal(usr)
if err != nil {
http.Error(w, "This is an error2", http.StatusBadRequest)
return
}
fmt.Fprintf(w, string(js))
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question