gate-editor-tool/main.go

73 lines
1.5 KiB
Go
Raw Permalink Normal View History

2024-12-15 00:30:04 +01:00
package gateeditor
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)
2024-12-15 00:47:32 +01:00
type Client struct {
url string
client *http.Client
}
2024-12-15 00:30:04 +01:00
func NewClient(url string) *Client {
return &Client{
2024-12-15 00:47:32 +01:00
url: url,
client: &http.Client{}, //optional, use for custom timeouts etc
2024-12-15 00:30:04 +01:00
}
}
type Route struct {
Host []string `json:"host"`
Backend string `json:"backend"`
}
2024-12-15 00:47:32 +01:00
type apiResponse struct {
Routes []Route `json:"routes"`
Message string `json:"message"`
Error string `json:"error"`
}
func (c *Client) doRequest(action string, payload interface{}) (*apiResponse, error) {
data, err := json.Marshal(map[string]interface{}{
"action": action,
"routes": payload,
})
2024-12-15 00:30:04 +01:00
if err != nil {
2024-12-15 00:47:32 +01:00
return nil, fmt.Errorf("failed marshalling payload: %w", err)
2024-12-15 00:30:04 +01:00
}
2024-12-15 00:47:32 +01:00
resp, err := c.client.Post(c.url, "application/json", bytes.NewBuffer(data))
if err != nil {
return nil, fmt.Errorf("failed to send request: %w", err)
2024-12-15 00:30:04 +01:00
}
2024-12-15 00:47:32 +01:00
defer resp.Body.Close()
var apiResp apiResponse
if err := json.NewDecoder(resp.Body).Decode(&apiResp); err != nil {
return nil, fmt.Errorf("failed to decode response: %w", err)
2024-12-15 00:30:04 +01:00
}
2024-12-15 00:47:32 +01:00
if apiResp.Error != "" {
return nil, fmt.Errorf("API error: %s", apiResp.Error)
2024-12-15 00:30:04 +01:00
}
2024-12-15 00:47:32 +01:00
return &apiResp, nil
2024-12-15 00:30:04 +01:00
}
2024-12-15 00:47:32 +01:00
func (c *Client) ListRoutes() ([]Route, error) {
resp, err := c.doRequest("ListRoutes", nil)
2024-12-15 00:30:04 +01:00
if err != nil {
2024-12-15 00:47:32 +01:00
return nil, err
2024-12-15 00:30:04 +01:00
}
2024-12-15 00:47:32 +01:00
return resp.Routes, nil
}
2024-12-15 00:30:04 +01:00
2024-12-15 00:47:32 +01:00
func (c *Client) UpdateRoutes(routes []Route) error {
_, err := c.doRequest("UpdateRoutes", routes)
return err
2024-12-15 00:30:04 +01:00
}
2024-12-15 00:47:32 +01:00