Search code examples
gosqlx

Undefined 'err' in SQLX when initializing connecting to a database


I am new to Go lang and trying to connect to the server and create a database upon an API call.

But I am getting an "undefined:err" at sqlx.Connect. Initially I thought it was because of me not defining the db *sqlx.DB. But it still gets error at db, err = sqlx.Connect("mysql", connection).

Is it necessary to define a var err ?

func (setupController *SetupController) Setup(w http.ResponseWriter, r *http.Request) {
    var db *sqlx.DB
    var connection string

    response := new(Response)
    response.Host = r.FormValue("host")
    response.Port = r.FormValue("port")
    response.Dbuser = r.FormValue("dbuser")
    response.Dbpassword = r.FormValue("dbpassword")
    response.Dbname = r.FormValue("dbname")
    response.Username = r.FormValue("username")
    response.Password = r.FormValue("password")

    connection = response.Dbuser + ":" + response.Dbpassword + "@tcp(" + response.Host + ":" + response.Port + ")/" + response.Dbname
    db, err = sqlx.Connect("mysql", connection)
    userJson, err := json.Marshal(response)
    if err != nil {
        panic(err)
    }

    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusOK)
    w.Write(userJson)
}

Thank you!


Solution

  • This is very basic Go. You should do the tour. In particular have a look at https://tour.golang.org/basics/10. Not that in Go you have to watch for the subtle difference between = and :=.

    But in brief you are using err before it is declared. You can either declare it first:

      var err error
    

    or use a short declaration

      db, err := sqlx.Connect("mysql", connection)
    

    Maybe easiest is to move the following line (which does do short declaration) before it otherwise you will get another error when it's declared twice. And you probably should also check the error.

      userJson, err := json.Marshal(response)
      if err != nil {
        panic(err)
      }
      db, err = sqlx.Connect("mysql", connection)
      if err != nil {
        panic(err)
      }
    

    However, I can see further problems beside this syntax error.