97 lines
1.5 KiB
Go
97 lines
1.5 KiB
Go
package boxy
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"log"
|
|
"net/http"
|
|
"strconv"
|
|
)
|
|
|
|
type BoxyClient struct {
|
|
Name string
|
|
Secret string
|
|
ApiUrl string
|
|
Hostnames []string
|
|
|
|
endpointId int
|
|
}
|
|
|
|
func (b *BoxyClient) Register(address string, port int) error {
|
|
rawBody := map[string]any{
|
|
"port": port,
|
|
"hostname": b.Hostnames,
|
|
}
|
|
|
|
if address != "" {
|
|
rawBody["address"] = address
|
|
}
|
|
|
|
jBody, err := json.Marshal(rawBody)
|
|
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
req, err := http.NewRequest("POST", b.ApiUrl+"/register", bytes.NewBuffer(jBody))
|
|
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
req.SetBasicAuth(b.Name, b.Secret)
|
|
|
|
resp, _ := http.DefaultClient.Do(req)
|
|
|
|
if resp.StatusCode != 200 {
|
|
log.Fatal("Could not register with Boxy.\nStatus Code: " + strconv.Itoa(req.Response.StatusCode))
|
|
}
|
|
|
|
body, err := io.ReadAll(resp.Body)
|
|
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
b.endpointId, err = strconv.Atoi(string(body))
|
|
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (b *BoxyClient) Unregister() error {
|
|
rawBody := map[string]any{}
|
|
|
|
jBody, err := json.Marshal(rawBody)
|
|
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
req, err := http.NewRequest("DELETE", b.ApiUrl+"/endpoint/"+strconv.Itoa(b.endpointId), bytes.NewBuffer(jBody))
|
|
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
req.SetBasicAuth(b.Name, b.Secret)
|
|
|
|
resp, _ := http.DefaultClient.Do(req)
|
|
|
|
body, err := io.ReadAll(resp.Body)
|
|
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if resp.StatusCode != 200 {
|
|
return fmt.Errorf("Could not delete endpoint.\nBody: %s", string(body))
|
|
}
|
|
|
|
return nil
|
|
}
|