ArinDash/apis/pihole/pihole.go

112 lines
2.0 KiB
Go

package pihole
import (
"ArinDash/config"
"encoding/json"
"io"
"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 {
if ph.Host == "" {
return make([]byte, 0)
}
var requestString = "http://" + ph.Host + "/api/" + endpoint
client := &http.Client{}
req, err := http.NewRequest(method, requestString, body)
if err != nil {
return make([]byte, 0)
}
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 {
return make([]byte, 0)
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return make([]byte, 0)
}
return respBody
}
var connector *PiHConnector
func Connect() PiHConnector {
if connector != nil {
return *connector
}
cfg := &configFile{}
config.LoadConfig(cfg)
client := &http.Client{}
if cfg.Pihole.Host == "" {
return PiHConnector{}
}
req, err := http.NewRequest("POST", "http://"+cfg.Pihole.Host+"/api/auth", strings.NewReader("{\"password\": \""+cfg.Pihole.Password+"\"}"))
if err != nil {
panic(err)
}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
panic(err)
}
s := &PiHAuth{}
err = json.Unmarshal(respBody, s)
if err != nil {
panic(err)
}
connector = &PiHConnector{
Host: cfg.Pihole.Host,
Session: s.Session,
}
return *connector
}