connector.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "encoding/json"
  6. "database/sql"
  7. _ "github.com/go-sql-driver/mysql"
  8. )
  9. type ConnectionProperties struct {
  10. User string
  11. Pass string
  12. Host string
  13. Db string
  14. }
  15. type connection struct {
  16. dBOpenStr string
  17. }
  18. func (c *connection) Init(filepath string){
  19. b, err := ioutil.ReadFile(filepath)
  20. if err != nil {
  21. fmt.Print(err)
  22. }
  23. propJson := string(b)
  24. var connProperties ConnectionProperties
  25. json.Unmarshal([]byte(propJson), &connProperties)
  26. fmt.Printf("Connection data:\n%s\n%s\n%s\n%s\n", connProperties.User, connProperties.Pass,connProperties.Host,connProperties.Db)
  27. c.dBOpenStr = connProperties.User + ":" + connProperties.Pass + "@tcp(" + connProperties.Host + ")/" + connProperties.Db
  28. fmt.Printf("Connecting with:\n%s\n", c.dBOpenStr)
  29. db, err := sql.Open("mysql", c.dBOpenStr)
  30. if err != nil {
  31. panic(err)
  32. }
  33. defer db.Close()
  34. }
  35. func (c connection) LogIn(username string, password string) bool{
  36. fmt.Printf("Connecting with:\n%s\n", c.dBOpenStr)
  37. db, err := sql.Open("mysql", c.dBOpenStr)
  38. if err != nil {
  39. panic(err)
  40. }
  41. defer db.Close()
  42. var counter int
  43. fmt.Printf("%s\n%s\n", username, password)
  44. act_query := "SELECT count(*) FROM gosite.users WHERE username='" + username + "' AND password='" + password + "';"
  45. db.QueryRow(act_query).Scan(&counter)
  46. fmt.Println("we have", counter, "rows")
  47. if (counter == 0) {
  48. return false
  49. }
  50. return true
  51. }
  52. /*
  53. func main() {
  54. var dBConnector connection
  55. dBConnector.Init("config.json")
  56. if (dBConnector.LogIn("Alex", "09Alex09")) {
  57. fmt.Printf("Succesfull logIn\n")
  58. } else {
  59. fmt.Printf("logIn error\n")
  60. }
  61. if (dBConnector.LogIn("Alax", "09Alex09")) {
  62. fmt.Printf("Succesfull logIn\n")
  63. } else {
  64. fmt.Printf("logIn error\n")
  65. }
  66. }
  67. */