我是 Go 语言的新手,尝试连接到服务器并在 API 调用时创建数据库。
但我在 处收到“未定义:错误” sqlx.Connect。最初我认为这是因为我没有定义db *sqlx.DB. 但它仍然出现错误db, err = sqlx.Connect("mysql", connection)。
是否有必要定义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)
}
谢谢你!
开心每一天1111
相关分类