101 lines
1.8 KiB
Go
101 lines
1.8 KiB
Go
package pihole
|
|
|
|
import (
|
|
"ArinDash/config"
|
|
"encoding/json"
|
|
"io"
|
|
"log"
|
|
"net/http"
|
|
"strings"
|
|
)
|
|
|
|
type configFile struct {
|
|
Pihole piholeConfig
|
|
}
|
|
|
|
type piholeConfig struct {
|
|
Host string
|
|
Password string
|
|
}
|
|
|
|
type PiHConnector struct {
|
|
Host string
|
|
Session PiHSession
|
|
}
|
|
|
|
type PiHAuth struct {
|
|
Session PiHSession `json:"session"`
|
|
}
|
|
|
|
type PiHSession struct {
|
|
SID string `json:"sid"`
|
|
CSRF string `json:"csrf"`
|
|
}
|
|
|
|
func (ph *PiHConnector) get(endpoint string) []byte {
|
|
return ph.do("GET", endpoint, nil)
|
|
}
|
|
|
|
func (ph *PiHConnector) post(endpoint string, body io.Reader) []byte {
|
|
return ph.do("POST", endpoint, body)
|
|
}
|
|
|
|
func (ph *PiHConnector) do(method string, endpoint string, body io.Reader) []byte {
|
|
var requestString = "http://" + ph.Host + "/api/" + endpoint
|
|
|
|
client := &http.Client{}
|
|
req, err := http.NewRequest(method, requestString, body)
|
|
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
req.Header.Add("X-FTL-SID", ph.Session.SID)
|
|
req.Header.Add("X-FTL-CSRF", ph.Session.CSRF)
|
|
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
respBody, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
return respBody
|
|
}
|
|
|
|
func Connect() PiHConnector {
|
|
cfg := &configFile{}
|
|
config.LoadConfig(cfg)
|
|
client := &http.Client{}
|
|
req, err := http.NewRequest("POST", "http://"+cfg.Pihole.Host+"/api/auth", strings.NewReader("{\"password\": \""+cfg.Pihole.Password+"\"}"))
|
|
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
respBody, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
s := &PiHAuth{}
|
|
|
|
err = json.Unmarshal(respBody, s)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
return PiHConnector{
|
|
Host: cfg.Pihole.Host,
|
|
Session: s.Session,
|
|
}
|
|
}
|