71 lines
1.8 KiB
Go
71 lines
1.8 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"io"
|
|
"net/http"
|
|
"strings"
|
|
)
|
|
|
|
type TrafficSettings struct {
|
|
Enabled bool `json:"enabled"`
|
|
AgentID string `json:"agentId"`
|
|
ServerCountry string `json:"serverCountry"`
|
|
}
|
|
|
|
func (s *Store) TrafficSettings() TrafficSettings {
|
|
var c TrafficSettings
|
|
s.loadJSONSetting("traffic", &c)
|
|
return c
|
|
}
|
|
func (s *Store) SaveTrafficSettings(c TrafficSettings) (TrafficSettings, error) {
|
|
c.AgentID = strings.TrimSpace(c.AgentID)
|
|
c.ServerCountry = strings.ToUpper(strings.TrimSpace(c.ServerCountry))
|
|
if c.Enabled {
|
|
var count int
|
|
if s.db.QueryRow(`SELECT COUNT(*) FROM agents WHERE id=?`, c.AgentID).Scan(&count) != nil || count != 1 {
|
|
return c, errors.New("Выберите зарегистрированный агент")
|
|
}
|
|
}
|
|
if c.ServerCountry != "" {
|
|
var countries []struct {
|
|
Code string `json:"code"`
|
|
}
|
|
json.Unmarshal(trafficWorld, &countries)
|
|
found := false
|
|
for _, country := range countries {
|
|
if country.Code == c.ServerCountry {
|
|
found = true
|
|
break
|
|
}
|
|
}
|
|
if !found {
|
|
return c, errors.New("Неизвестная страна сервера")
|
|
}
|
|
}
|
|
return c, s.saveJSONSetting("traffic", c)
|
|
}
|
|
func trafficSettingsRoute(mux *http.ServeMux, s *Store) {
|
|
mux.HandleFunc("/api/settings/traffic", func(w http.ResponseWriter, r *http.Request) {
|
|
switch r.Method {
|
|
case "GET":
|
|
writeJSON(w, s.TrafficSettings(), nil)
|
|
case "PUT":
|
|
var c TrafficSettings
|
|
if json.NewDecoder(io.LimitReader(r.Body, 4096)).Decode(&c) != nil {
|
|
http.Error(w, "Некорректные настройки", 400)
|
|
return
|
|
}
|
|
value, err := s.SaveTrafficSettings(c)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), 400)
|
|
return
|
|
}
|
|
writeJSON(w, value, nil)
|
|
default:
|
|
w.WriteHeader(405)
|
|
}
|
|
})
|
|
}
|