dbconnector.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. act_query := "SELECT count(*) FROM gosite.users WHERE username='" + username + "' AND password='" + password + "';"
  44. db.QueryRow(act_query).Scan(&counter)
  45. fmt.Println("we have", counter, "rows")
  46. if (counter == 0) {
  47. return false
  48. }
  49. return true
  50. }
  51. /*
  52. func main() {
  53. var dBConnector connection
  54. dBConnector.Init("config.json")
  55. if (dBConnector.LogIn("Alex", "09Alex09")) {
  56. fmt.Printf("Succesfull logIn\n")
  57. } else {
  58. fmt.Printf("logIn error\n")
  59. }
  60. if (dBConnector.LogIn("Alax", "09Alex09")) {
  61. fmt.Printf("Succesfull logIn\n")
  62. } else {
  63. fmt.Printf("logIn error\n")
  64. }
  65. }
  66. */