2015-09-04 86 views
0

爲什麼我的defer stmnt.Close()似乎阻止我的http.Redirect重定向它只是掛在網站上無限加載。爲什麼推遲stmnt.Close()似乎阻止我的http.Redirect?

但是,如果我刪除defer stmnt.Close()它重定向就好了嗎?

err = db.QueryRow("SELECT steamid FROM accounts WHERE steamid = ?", ids).Scan(&steamid) 
    if err != nil { 
     common.WriteLog(err.Error(), r) 
     http.Error(w, "Failed to connect to database. Try again in a bit.", 500) 
    } 

    switch { 
    case len(profile.Response.Players) == 0: 
     common.WriteLog("Failed to look you up in the steam database. Try again in a bit.", r) 
     http.Error(w, "Failed to look you up in the steam database. Try again in a bit.", 500) 
    case err == sql.ErrNoRows: 
     stmnt, err := db.Query("INSERT INTO accounts SET steamid=?", ids) 
     if err != nil { 
      common.WriteLog(err.Error(), r) 
      http.Error(w, "Failed to insert your account to the database. Try again in a bit.", 500) 
     } 
     defer stmnt.Close() // <<<<< The suspect 
     // Insert Account 

     http.Redirect(w, r, "/", 303) 
    case err != nil: 
     common.WriteLog(err.Error(), r) 
     http.Error(w, "Failed to insert your account to the database. Try again in a bit.", 500) 

    default: 
     // Login User 

     http.Redirect(w, r, "/", 303) 

    } 

回答

3

使用db.Exec而不是db.Query

Exec在不返回任何行的情況下執行查詢。

VS

查詢執行返回行

至於爲什麼,我猜mysql的Rows.Close查詢正在等待數據on the connection

func (rows *mysqlRows) Close() error { 
    mc := rows.mc 
    if mc == nil { 
     return nil 
    } 
    if mc.netConn == nil { 
     return ErrInvalidConn 
    } 

    // Remove unread packets from stream 
    err := mc.readUntilEOF() 
    rows.mc = nil 
    return err 
} 

哪永遠不會發生。

例如參見this