All checks were successful
Gitea Actions Demo / Run-Python-Script (push) Successful in 4s
104 lines
2.3 KiB
Go
104 lines
2.3 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"os"
|
|
)
|
|
|
|
type AdGuardClient struct {
|
|
BaseURL string
|
|
Username string
|
|
Password string
|
|
Client *http.Client
|
|
}
|
|
|
|
func NewAdGuardClient() (*AdGuardClient, error) {
|
|
baseURL := os.Getenv("ADGUARD_URL")
|
|
user := os.Getenv("ADGUARD_USER")
|
|
pass := os.Getenv("ADGUARD_PASSWORD")
|
|
|
|
if baseURL == "" || user == "" || pass == "" {
|
|
return nil, fmt.Errorf("fehlende Umgebungsvariablen")
|
|
}
|
|
|
|
return &AdGuardClient{
|
|
BaseURL: baseURL,
|
|
Username: user,
|
|
Password: pass,
|
|
Client: &http.Client{},
|
|
}, nil
|
|
}
|
|
|
|
func (c *AdGuardClient) Login() error {
|
|
data := map[string]string{"name": c.Username, "password": c.Password}
|
|
return c.post("/control/login", data, nil)
|
|
}
|
|
|
|
func (c *AdGuardClient) GetRewrites() ([]Rewrite, error) {
|
|
resp, err := c.Client.Get(c.BaseURL + "/control/rewrite/list")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
var list []Rewrite
|
|
if err := json.NewDecoder(resp.Body).Decode(&list); err != nil {
|
|
return nil, err
|
|
}
|
|
return list, nil
|
|
}
|
|
|
|
func (c *AdGuardClient) AddRewrite(r Rewrite) error {
|
|
return c.post("/control/rewrite/add", r, nil)
|
|
}
|
|
|
|
func (c *AdGuardClient) DeleteRewrite(r Rewrite) error {
|
|
return c.post("/control/rewrite/delete", r, nil)
|
|
}
|
|
|
|
func (c *AdGuardClient) UpdateRewrite(oldR, newR Rewrite) error {
|
|
payload := map[string]Rewrite{"target": oldR, "update": newR}
|
|
return c.put("/control/rewrite/update", payload, nil)
|
|
}
|
|
|
|
func (c *AdGuardClient) post(path string, body any, result any) error {
|
|
return c.doRequest("POST", path, body, result)
|
|
}
|
|
|
|
func (c *AdGuardClient) put(path string, body any, result any) error {
|
|
return c.doRequest("PUT", path, body, result)
|
|
}
|
|
|
|
func (c *AdGuardClient) doRequest(method, path string, body any, result any) error {
|
|
b, err := json.Marshal(body)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
req, err := http.NewRequest(method, c.BaseURL+path, bytes.NewReader(b))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
req.Header.Set("Content-Type", "application/json")
|
|
|
|
resp, err := c.Client.Do(req)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
if resp.StatusCode >= 400 {
|
|
body, _ := io.ReadAll(resp.Body)
|
|
return fmt.Errorf("Fehler %d: %s", resp.StatusCode, string(body))
|
|
}
|
|
|
|
if result != nil {
|
|
return json.NewDecoder(resp.Body).Decode(result)
|
|
}
|
|
return nil
|
|
}
|