2023-12-08 22:02:36 +08:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"net/http"
|
|
|
|
"os"
|
|
|
|
|
|
|
|
"git.pyer.club/kingecg/gohttpd/admin"
|
2023-12-09 17:08:31 +08:00
|
|
|
handler "git.pyer.club/kingecg/gohttpd/hander"
|
2023-12-08 22:02:36 +08:00
|
|
|
"git.pyer.club/kingecg/gohttpd/model"
|
|
|
|
"git.pyer.club/kingecg/gohttpd/server"
|
|
|
|
"git.pyer.club/kingecg/gologger"
|
|
|
|
)
|
|
|
|
|
|
|
|
type GoHttp struct {
|
|
|
|
conf model.GoHttpdConfig
|
|
|
|
logger gologger.Logger
|
|
|
|
}
|
|
|
|
|
|
|
|
func (g *GoHttp) Start() {
|
|
|
|
g.logger.Info("start gohttpd")
|
|
|
|
// if g.conf != nil {
|
|
|
|
port := model.DefaultAdminConfig.Port
|
|
|
|
if g.conf.Admin != nil {
|
|
|
|
port = g.conf.Admin.Port
|
|
|
|
}
|
|
|
|
|
|
|
|
g.makeServer("admin", port, admin.AdminServerMux)
|
|
|
|
|
2023-12-09 17:08:31 +08:00
|
|
|
for _, server := range g.conf.Servers {
|
|
|
|
sHandler := g.assembleServerMux(server.Paths)
|
|
|
|
g.makeServer(server.ServerName, server.Port, sHandler)
|
|
|
|
}
|
2023-12-08 22:02:36 +08:00
|
|
|
|
|
|
|
for _, listener := range server.ServerManager {
|
|
|
|
listener.Start()
|
|
|
|
listener.Serve()
|
|
|
|
|
|
|
|
}
|
|
|
|
g.logger.Info("gohttpd start success")
|
|
|
|
}
|
|
|
|
|
2023-12-09 17:08:31 +08:00
|
|
|
func (g *GoHttp) makeServer(name string, port int, mux http.Handler) {
|
2023-12-08 22:02:36 +08:00
|
|
|
s := &http.Server{
|
|
|
|
Handler: mux,
|
|
|
|
}
|
|
|
|
server.AddServer(name, s, port)
|
|
|
|
}
|
|
|
|
|
2023-12-09 17:08:31 +08:00
|
|
|
func (g *GoHttp) assembleServerMux(p []model.HttpPath) http.Handler {
|
|
|
|
s := http.NewServeMux()
|
|
|
|
for _, httpPath := range p {
|
|
|
|
if httpPath.Root != "" {
|
|
|
|
fileHandler := handler.NewFileHandler(handler.FileHandler{
|
|
|
|
Root: httpPath.Root,
|
|
|
|
Default: httpPath.Default,
|
|
|
|
})
|
|
|
|
s.Handle(httpPath.Path, fileHandler)
|
|
|
|
} else if len(httpPath.Upstreams) != 0 {
|
|
|
|
proxyHandler := handler.NewProxyHandler(&httpPath)
|
|
|
|
s.Handle(httpPath.Path, proxyHandler)
|
|
|
|
} else {
|
|
|
|
g.logger.Error("Not supportted server path type :", httpPath.Path)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return s
|
|
|
|
}
|
|
|
|
|
2023-12-08 22:02:36 +08:00
|
|
|
func (g *GoHttp) Stop() {}
|
|
|
|
|
|
|
|
func (g *GoHttp) LoadConfig(configPath string) {
|
|
|
|
cpath := configPath
|
|
|
|
if cpath == "" {
|
|
|
|
cpath = GetExecDir() + "/config.json"
|
|
|
|
}
|
|
|
|
|
|
|
|
// read content from cpath
|
|
|
|
content, _ := os.ReadFile(cpath)
|
|
|
|
json.Unmarshal(content, &g.conf)
|
|
|
|
gologger.Configure(g.conf.Logging)
|
|
|
|
g.logger = gologger.GetLogger("Server")
|
|
|
|
g.logger.Info("Load config success")
|
|
|
|
}
|