Browse Source

Feature/domain binding (#3)

* Host/Domain bindings

* Make method private

* Domain/host mapping optimization

* Reread domains every http call
Vova Tkach 6 years ago
parent
commit
287cfa76cf
3 changed files with 75 additions and 2 deletions
  1. 2 1
      .gitignore
  2. 64 0
      domains/domains.go
  3. 9 1
      main.go

+ 2 - 1
.gitignore

@@ -24,7 +24,8 @@
 !/hosts/*/tmp/.*
 
 # Test virtual host dir
-/hosts/example.com
+/hosts/*
+!/hosts/localhost
 
 # Default host mysql config file
 /hosts/localhost/config/mysql.json

+ 64 - 0
domains/domains.go

@@ -0,0 +1,64 @@
+package domains
+
+import (
+	"bufio"
+	"io/ioutil"
+	"os"
+	"strings"
+	"sync"
+
+	"golang-fave/utils"
+)
+
+type Domains struct {
+	sync.RWMutex
+	hosts map[string]string
+}
+
+func New(www_dir string) *Domains {
+	r := Domains{}
+	r.hosts = map[string]string{}
+
+	files, err := ioutil.ReadDir(www_dir)
+	if err == nil {
+		for _, file := range files {
+			domains_file := www_dir + string(os.PathSeparator) + file.Name() +
+				string(os.PathSeparator) + "config" + string(os.PathSeparator) + ".domains"
+			if utils.IsFileExists(domains_file) {
+				if f, err := os.Open(domains_file); err == nil {
+					defer f.Close()
+					reader := bufio.NewReader(f)
+					var domain string
+					for {
+						domain, err = reader.ReadString('\n')
+						if err != nil {
+							break
+						}
+						if strings.TrimSpace(domain) != "" {
+							r.addDmain(file.Name(), strings.TrimSpace(domain))
+						}
+					}
+				}
+			}
+		}
+	}
+
+	return &r
+}
+
+func (this *Domains) addDmain(host string, domain string) {
+	this.Lock()
+	defer this.Unlock()
+	if _, ok := this.hosts[domain]; ok == false {
+		this.hosts[domain] = host
+	}
+}
+
+func (this *Domains) GetHost(domain string) string {
+	this.Lock()
+	defer this.Unlock()
+	if value, ok := this.hosts[domain]; ok == true {
+		return value
+	}
+	return ""
+}

+ 9 - 1
main.go

@@ -9,6 +9,7 @@ import (
 
 	"golang-fave/assets"
 	"golang-fave/consts"
+	"golang-fave/domains"
 	"golang-fave/engine"
 	"golang-fave/engine/mysqlpool"
 	"golang-fave/logger"
@@ -107,7 +108,14 @@ func main() {
 		// Host and port
 		host, port := utils.ExtractHostPort(r.Host, false)
 		curr_host := host
-		vhost_dir := consts.ParamWwwDir + string(os.PathSeparator) + host
+
+		// Domain bindings
+		doms := domains.New(consts.ParamWwwDir)
+		if mhost := doms.GetHost(host); mhost != "" {
+			curr_host = mhost
+		}
+
+		vhost_dir := consts.ParamWwwDir + string(os.PathSeparator) + curr_host
 		if !utils.IsDirExists(vhost_dir) {
 			curr_host = "localhost"
 			vhost_dir = consts.ParamWwwDir + string(os.PathSeparator) + "localhost"