🎉 Initial Commit

This commit is contained in:
2023-11-16 23:06:59 +08:00
commit 2fc1ef89db
13 changed files with 1010 additions and 0 deletions

58
pkg/configurator/main.go Normal file
View File

@ -0,0 +1,58 @@
package configurator
import (
"encoding/json"
"io"
"os"
"path/filepath"
"strings"
)
var C *AppConfig
func ReadInConfig(root string) error {
cfg := &AppConfig{
Sites: []SiteConfig{},
}
if err := filepath.Walk(root, func(fp string, info os.FileInfo, err error) error {
var site SiteConfig
if info.IsDir() {
return nil
} else if file, err := os.OpenFile(fp, os.O_RDONLY, 0755); err != nil {
return err
} else if data, err := io.ReadAll(file); err != nil {
return err
} else if err := json.Unmarshal(data, &site); err != nil {
return err
} else {
// Extract file name as site id
site.ID = strings.SplitN(filepath.Base(fp), ".", 2)[0]
cfg.Sites = append(cfg.Sites, site)
}
return nil
}); err != nil {
return err
}
C = cfg
return nil
}
func SaveInConfig(root string, cfg *AppConfig) error {
for _, site := range cfg.Sites {
data, _ := json.Marshal(site)
fp := filepath.Join(root, site.ID)
if file, err := os.OpenFile(fp, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0755); err != nil {
return err
} else if _, err := file.Write(data); err != nil {
return err
}
}
return nil
}

View File

@ -0,0 +1,46 @@
package configurator
import "strings"
type AppConfig struct {
Sites []SiteConfig `json:"sites"`
}
type SiteConfig struct {
ID string `json:"id"`
Name string `json:"name"`
Rules []RouterRuleConfig `json:"rules"`
Upstreams []UpstreamConfig `json:"upstreams"`
}
type RouterRuleConfig struct {
Host []string `json:"host"`
Path []string `json:"path"`
Queries map[string]string `json:"query"`
Headers map[string][]string `json:"headers"`
}
const (
UpstreamTypeFile = "file"
UpstreamTypeHypertext = "hypertext"
UpstreamTypeUnknown = "unknown"
)
type UpstreamConfig struct {
Name string `json:"name"`
URI string `json:"uri"`
}
func (v *UpstreamConfig) GetType() string {
protocol := strings.SplitN(v.URI, "://", 2)[0]
switch protocol {
case "file":
return UpstreamTypeFile
case "http":
case "https":
return UpstreamTypeHypertext
}
return UpstreamTypeUnknown
}