package main import ( "fmt" "io/ioutil" "encoding/json" "database/sql" _ "github.com/go-sql-driver/mysql" ) type ConnectionProperties struct { User string Pass string Host string Db string } type connection struct { dBOpenStr string } func (c *connection) Init(filepath string){ b, err := ioutil.ReadFile(filepath) if err != nil { fmt.Print(err) } propJson := string(b) var connProperties ConnectionProperties json.Unmarshal([]byte(propJson), &connProperties) fmt.Printf("Connection data:\n%s\n%s\n%s\n%s\n", connProperties.User, connProperties.Pass,connProperties.Host,connProperties.Db) c.dBOpenStr = connProperties.User + ":" + connProperties.Pass + "@tcp(" + connProperties.Host + ")/" + connProperties.Db fmt.Printf("Connecting with:\n%s\n", c.dBOpenStr) db, err := sql.Open("mysql", c.dBOpenStr) if err != nil { panic(err) } defer db.Close() } func (c connection) LogIn(username string, password string) bool{ fmt.Printf("Connecting with:\n%s\n", c.dBOpenStr) db, err := sql.Open("mysql", c.dBOpenStr) if err != nil { panic(err) } defer db.Close() var counter int fmt.Printf("%s\n%s\n", username, password) act_query := "SELECT count(*) FROM gosite.users WHERE username='" + username + "' AND password='" + password + "';" db.QueryRow(act_query).Scan(&counter) fmt.Println("we have", counter, "rows") if (counter == 0) { return false } return true } func (c connection) IsNameUsed(username string) bool { db, err := sql.Open("mysql", c.dBOpenStr) if err != nil { panic(err) } defer db.Close() var counter int act_query := "SELECT count(*) FROM gosite.users WHERE username='" + username + "';" db.QueryRow(act_query).Scan(&counter) if (counter == 0) { fmt.Printf("Username unused\n") return false } fmt.Printf("Username used\n") return true } func (c connection) SigInUser(username string, password string) bool { db, err := sql.Open("mysql", c.dBOpenStr) if err != nil { panic(err) } defer db.Close() result, err := db.Exec("INSERT INTO gosite.users (username, password) values (?, ?)", username, password) if err != nil{ panic(err) } rowsCount, _ := result.RowsAffected() if (rowsCount == 1) { fmt.Printf("Lines changed: %d\n", rowsCount) return true } else { return false } } /* func main() { var dBConnector connection dBConnector.Init("config.json") if (dBConnector.LogIn("Alex", "09Alex09")) { fmt.Printf("Succesfull logIn\n") } else { fmt.Printf("logIn error\n") } if (dBConnector.LogIn("Alax", "09Alex09")) { fmt.Printf("Succesfull logIn\n") } else { fmt.Printf("logIn error\n") } } */