2023-12-07 00:22:53 +08:00
|
|
|
package model
|
|
|
|
|
2023-12-13 17:59:14 +08:00
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"os"
|
|
|
|
|
|
|
|
"git.pyer.club/kingecg/gohttpd/utils"
|
|
|
|
"git.pyer.club/kingecg/gologger"
|
|
|
|
)
|
2023-12-08 22:02:36 +08:00
|
|
|
|
2023-12-07 00:22:53 +08:00
|
|
|
type HttpPath struct {
|
2023-12-09 16:34:20 +08:00
|
|
|
Path string `json:"path"`
|
|
|
|
Root string `json:"root"`
|
|
|
|
Default string `json:"default"`
|
|
|
|
Upstreams []string `json:"upstreams"`
|
|
|
|
Rewrite PathRewrite `json:"pathrewrite"`
|
|
|
|
}
|
|
|
|
|
|
|
|
type PathRewrite struct {
|
|
|
|
Replace string `json:"replace"`
|
|
|
|
With string `json:"with"`
|
2023-12-07 00:22:53 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
type HttpServerConfig struct {
|
2023-12-11 18:15:29 +08:00
|
|
|
Name string `json:"name"`
|
2023-12-07 00:22:53 +08:00
|
|
|
ServerName string `json:"server"`
|
|
|
|
Port int `json:"port"`
|
|
|
|
Host string `json:"host"`
|
|
|
|
Paths []HttpPath
|
2023-12-11 18:15:29 +08:00
|
|
|
Username string `json:"username"`
|
|
|
|
Password string `json:"password"`
|
2023-12-13 09:22:05 +08:00
|
|
|
CertFile string `json:"certfile"`
|
|
|
|
KeyFile string `json:"keyfile"`
|
2023-12-07 00:22:53 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
type GoHttpdConfig struct {
|
2023-12-08 22:02:36 +08:00
|
|
|
Logging gologger.LoggersConfig `json:"logging"`
|
|
|
|
Admin *HttpServerConfig `json:"admin"`
|
|
|
|
Servers []*HttpServerConfig `json:"servers"`
|
2023-12-07 00:22:53 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
var DefaultAdminConfig HttpServerConfig = HttpServerConfig{
|
|
|
|
ServerName: "admin",
|
|
|
|
Port: 8080,
|
|
|
|
}
|
2023-12-11 18:15:29 +08:00
|
|
|
|
|
|
|
var Config GoHttpdConfig = GoHttpdConfig{}
|
|
|
|
|
|
|
|
func GetConfig() *GoHttpdConfig {
|
|
|
|
return &Config
|
|
|
|
}
|
|
|
|
|
2023-12-13 17:59:14 +08:00
|
|
|
func SetServerConfig(c *HttpServerConfig) error {
|
|
|
|
l := gologger.GetLogger("model")
|
|
|
|
updated := false
|
2023-12-11 18:15:29 +08:00
|
|
|
for i, s := range Config.Servers {
|
|
|
|
if s.Name == c.Name {
|
|
|
|
Config.Servers[i] = c
|
2023-12-13 17:59:14 +08:00
|
|
|
updated = true
|
|
|
|
break
|
2023-12-11 18:15:29 +08:00
|
|
|
}
|
|
|
|
}
|
2023-12-13 17:59:14 +08:00
|
|
|
if !updated {
|
|
|
|
Config.Servers = append(Config.Servers, c)
|
|
|
|
}
|
|
|
|
configFile := utils.NormalizePath("./config.json")
|
|
|
|
configsStr, err := json.Marshal(Config)
|
|
|
|
if err != nil {
|
|
|
|
l.Error("Save config error:", err)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
werr := os.WriteFile(configFile, configsStr, 0644)
|
|
|
|
if werr != nil {
|
|
|
|
l.Error("Save config error:", werr)
|
|
|
|
return werr
|
|
|
|
}
|
|
|
|
return nil
|
2023-12-11 18:15:29 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func GetServerConfig(name string) *HttpServerConfig {
|
|
|
|
for _, s := range Config.Servers {
|
|
|
|
if s.Name == name {
|
|
|
|
return s
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|