Api主要代码,点击我找跟此文章标题一样的commit,此阶段源码
package dbops
import (
"log"
_ "github.com/go-sql-driver/mysql"
"database/sql"
)
func AddUserCredential(loginName string, pwd string) error {
stmtIns, err := dbConn.Prepare("INSERT INTO users (login_name, pwd) VALUES (?,?)")
if err!=nil {
return err
}
_, err = stmtIns.Exec(loginName, pwd)
if err!=nil {
return err
}
defer stmtIns.Close() // 性能消耗较大
return nil
}
func GetUserCredential(loginName string) (string, error) {
stmtOut, err := dbConn.Prepare("SELECT pwd FROM users WHERE login_name = ?")
if err != nil {
log.Printf("%s", err)
return "", err
}
var pwd string
err = stmtOut.QueryRow(loginName).Scan(&pwd)
// noRows 没有结果返回
if err != nil && err != sql.ErrNoRows {
return "", err
}
defer stmtOut.Close()
return pwd, nil
}
func DeleteUser(loginName string, pwd string) error {
stmtDel, err := dbConn.Prepare("DELETE FROM users WHERE login_name = ?")
if err != nil {
log.Printf("DeleteUser error: %s", err)
return err
}
stmtDel.Exec(loginName, pwd)
if err != nil && err != sql.ErrNoRows {
return err
}
defer stmtDel.Close()
return nil
}
测试
package dbops
import (
"testing"
)
func clearTables() {
dbConn.Exec("truncate users")
dbConn.Exec("truncate video_info")
dbConn.Exec("truncate comments")
dbConn.Exec("truncate sessions")
}
func TestMain(m *testing.M) {
clearTables()
m.Run()
clearTables()
}
func TestUserWorkFlow(t *testing.T) {
t.Run("Add", testAddUser)
t.Run("Get", testGetUser)
t.Run("Del", testDeleteUser)
t.Run("Reget", testRegetUser)
}
func testAddUser(t *testing.T) {
err := AddUserCredential("tuzisir", "123")
if err != nil {
// %v 是以默认方式打印此值
t.Errorf("Error of AddUser: %v", err)
}
}
func testGetUser(t *testing.T) {
pwd, err := GetUserCredential("tuzisir")
if pwd != "123" || err != nil {
t.Errorf("Error of GetUser: %v", err)
}
}
func testDeleteUser(t *testing.T) {
err := DeleteUser("tuzisir", "123")
if err != nil {
t.Errorf("Error of DeleteUser: %v", err)
}
}
func testRegetUser(t *testing.T) {
pwd, err := GetUserCredential("tuzisir")
if err != nil {
t.Errorf("Error of RegetUser: %v", err)
}
if pwd == "" {
t.Errorf("Reget user test fail")
}
}
image.png结果
网友评论