gate-editor-tool/main.go

77 lines
1.5 KiB
Go
Raw Normal View History

2024-12-15 00:30:04 +01:00
package gateeditor
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)
func NewClient(url string) *Client {
return &Client{
url: url,
}
}
type Client struct {
url string
}
type Route struct {
Host []string `json:"host"`
Backend string `json:"backend"`
}
func (c *Client) listRoutes() ([]Route, error) {
body := bytes.NewBufferString(`{"action": "ListRoutes"}`)
resp, err := http.Post(c.url, "application/json", body)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var response struct {
Routes []Route `json:"routes"`
Error string `json:"error"`
}
if err := json.NewDecoder(resp.Body).Decode(&response); err != nil {
return nil, err
}
if response.Error != "" {
return nil, fmt.Errorf("error listing routes: %s", response.Error)
}
return response.Routes, nil
}
func (c *Client) updateRoutes(routes []Route) error {
payload := struct {
Action string `json:"action"`
Routes []Route `json:"routes"`
}{
Action: "UpdateRoutes",
Routes: routes,
}
payloadBytes, err := json.Marshal(payload)
if err != nil {
return err
}
resp, err := http.Post(c.url, "application/json", bytes.NewBuffer(payloadBytes))
if err != nil {
return err
}
defer resp.Body.Close()
var response struct {
Message string `json:"message"`
Error string `json:"error"`
}
if err := json.NewDecoder(resp.Body).Decode(&response); err != nil {
return err
}
if response.Error != "" {
return fmt.Errorf("error updating routes: %s", response.Error)
}
return nil
}