Idiomatic Go and MySQL models

I’m new to Go and I have a question regarding dependencies that I’m trying to pass down to my models. While my code is working perfectly, I’m still not sure if my way is idiomatic or it’s fine and up to my preferences.

I started writing simple REST API using core HTTP package, Gorilla mux and official mysql package.

My project structure is as follows:

In ~/go/src/<myhandle>/<project>
(project root dir)
   - (db)
      - database.go
   - (models)
      - (user)
         - user.go
   - (controllers)
      - (user)
         - user.go
   - main.go

I’ve initialized database connection in main.go and I pass it down to controllers.


ctrs := router.InitializeRouter(mux, ctr_user.Routes(db), ...)
log.Fatal(http.ListenAndServe(":3000", ctrs))


This is just example, it’s pretty static and I know I shouldn’t be using GET here.

type Ctx struct {
    Subrouter *mux.Router
    DB        *sql.DB

func (ctx *Ctx) Register(w http.ResponseWriter, r *http.Request) {
    user := users.UserRegister{Username: "newuser", Email: "", Password: "blah", DB: ctx.DB}

func Routes(db *sql.DB) *ctx.Controller {
    mux := mux.NewRouter()
    ctr := &Ctx{Subrouter: mux, DB: db}
    ctr.Subrouter.HandleFunc("/", ctr.Register).Methods("GET")
    return &ctx.Controller{Path: "/users", Controller: mux}


type UserRegister struct {
    Username string `json:"username"`
    Email    string `json:"email"`
    Password string `json:"password"`
    DB       *sql.DB
func (u *UserRegister) New() {
    res, err := u.DB.Exec(`INSERT INTO users(username,email,hash) VALUES(?,?,?)`, u.Username, u.Email, u.Password)
    if err != nil {
    id, _ := res.LastInsertId()
    fmt.Println("User added with ID: ", id)

So the code works, but I have no idea if this is the way it should be done. Primarily the way DB instance was handed down to model from controller.

I’ve seen examples on github where DB is passed down as parameter, like this:

func (u *UserRegister) New(db *sql.DB) {
     res, err := db.Exec(...)

So am I doing this wrong or it’s up to my preference?