Browse Source

MySQL for actions by request

Vova Tkach 6 years ago
parent
commit
7c79cc997d
2 changed files with 38 additions and 1 deletions
  1. 7 0
      engine/actions/action_signin.go
  2. 31 1
      engine/actions/actions.go

+ 7 - 0
engine/actions/action_signin.go

@@ -1,5 +1,12 @@
 package actions
 
 func (this *Action) Action_signin() {
+	if dbe := this.use_database(); dbe != nil {
+		this.msg_error(dbe.Error())
+		return
+	} else {
+		defer this.db.Close()
+	}
+
 	this.msg_success(`Hello from web server`)
 }

+ 31 - 1
engine/actions/actions.go

@@ -1,15 +1,22 @@
 package actions
 
 import (
+	"database/sql"
+	_ "github.com/go-sql-driver/mysql"
+
+	"errors"
 	"fmt"
 	"reflect"
 	"strings"
 
 	"golang-fave/engine/wrapper"
+
+	utils "golang-fave/engine/wrapper/utils"
 )
 
 type Action struct {
 	wrapper *wrapper.Wrapper
+	db      *sql.DB
 }
 
 func (this *Action) write(data string) {
@@ -31,8 +38,31 @@ func (this *Action) msg_error(msg string) {
 	this.msg_show("Error", msg)
 }
 
+func (this *Action) use_database() error {
+	if this.db != nil {
+		return errors.New("already connected to database")
+	}
+	if !utils.IsMySqlConfigExists(this.wrapper.DirVHostHome) {
+		return errors.New("can't read database configuration file")
+	}
+	mc, err := utils.MySqlConfigRead(this.wrapper.DirVHostHome)
+	if err != nil {
+		return err
+	}
+	this.db, err = sql.Open("mysql", mc.User+":"+mc.Password+"@tcp("+mc.Host+":"+mc.Port+")/"+mc.Name)
+	if err != nil {
+		return err
+	}
+	err = this.db.Ping()
+	if err != nil {
+		this.db.Close()
+		return err
+	}
+	return nil
+}
+
 func New(wrapper *wrapper.Wrapper) *Action {
-	return &Action{wrapper}
+	return &Action{wrapper, nil}
 }
 
 func (this *Action) Run() bool {