Add: config hub route
This commit is contained in:
67
hub/configs.go
Normal file
67
hub/configs.go
Normal file
@ -0,0 +1,67 @@
|
||||
package hub
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/chi"
|
||||
"github.com/go-chi/render"
|
||||
)
|
||||
|
||||
type Configs struct {
|
||||
Proxys []Proxy `json:"proxys"`
|
||||
Rules []Rule `json:"rules"`
|
||||
}
|
||||
|
||||
type Proxy struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
type Rule struct {
|
||||
Name string `json:"name"`
|
||||
Payload string `json:"type"`
|
||||
}
|
||||
|
||||
func configRouter() http.Handler {
|
||||
r := chi.NewRouter()
|
||||
r.Get("/", getConfig)
|
||||
r.Put("/", updateConfig)
|
||||
return r
|
||||
}
|
||||
|
||||
func getConfig(w http.ResponseWriter, r *http.Request) {
|
||||
rulesCfg, proxysCfg := tun.Config()
|
||||
|
||||
var (
|
||||
rules []Rule
|
||||
proxys []Proxy
|
||||
)
|
||||
|
||||
for _, rule := range rulesCfg {
|
||||
rules = append(rules, Rule{
|
||||
Name: rule.RuleType().String(),
|
||||
Payload: rule.Payload(),
|
||||
})
|
||||
}
|
||||
|
||||
for _, proxy := range proxysCfg {
|
||||
proxys = append(proxys, Proxy{Name: proxy.Name()})
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
render.JSON(w, r, Configs{
|
||||
Rules: rules,
|
||||
Proxys: proxys,
|
||||
})
|
||||
}
|
||||
|
||||
func updateConfig(w http.ResponseWriter, r *http.Request) {
|
||||
err := tun.UpdateConfig()
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
render.JSON(w, r, Error{
|
||||
Error: err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
@ -35,6 +35,7 @@ func NewHub(addr string) {
|
||||
|
||||
r.Get("/traffic", traffic)
|
||||
r.Get("/logs", getLogs)
|
||||
r.Mount("/configs", configRouter())
|
||||
|
||||
err := http.ListenAndServe(addr, r)
|
||||
if err != nil {
|
||||
@ -43,7 +44,7 @@ func NewHub(addr string) {
|
||||
}
|
||||
|
||||
func traffic(w http.ResponseWriter, r *http.Request) {
|
||||
render.Status(r, http.StatusOK)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
|
||||
tick := time.NewTicker(time.Second)
|
||||
t := tun.Traffic()
|
||||
@ -64,10 +65,11 @@ func getLogs(w http.ResponseWriter, r *http.Request) {
|
||||
sub, err := src.Subscribe()
|
||||
defer src.UnSubscribe(sub)
|
||||
if err != nil {
|
||||
render.Status(r, http.StatusInternalServerError)
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
render.JSON(w, r, Error{
|
||||
Error: err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
render.Status(r, http.StatusOK)
|
||||
for elm := range sub {
|
||||
|
Reference in New Issue
Block a user