This commit is contained in:
@@ -0,0 +1,83 @@
|
||||
// Package shelly provides HTTP communication shared by Shelly product implementations.
|
||||
package shelly
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const maxErrorBodySize = 4 * 1024
|
||||
|
||||
// StatusClient is consumed by product collectors and can be replaced in tests.
|
||||
type StatusClient interface {
|
||||
GetStatus(context.Context, any) error
|
||||
}
|
||||
|
||||
// Client fetches status data from one Shelly device.
|
||||
type Client struct {
|
||||
baseURL *url.URL
|
||||
username string
|
||||
password string
|
||||
httpClient *http.Client
|
||||
}
|
||||
|
||||
// NewClient creates a client that uses HTTP Basic Authentication when credentials are set.
|
||||
func NewClient(rawURL, username, password string, timeout time.Duration) (*Client, error) {
|
||||
baseURL, err := url.Parse(rawURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse Shelly URL: %w", err)
|
||||
}
|
||||
|
||||
return &Client{
|
||||
baseURL: baseURL,
|
||||
username: username,
|
||||
password: password,
|
||||
httpClient: &http.Client{
|
||||
Timeout: timeout,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// GetStatus decodes the /status response into destination.
|
||||
func (c *Client) GetStatus(ctx context.Context, destination any) error {
|
||||
statusURL := *c.baseURL
|
||||
statusURL.Path = strings.TrimRight(statusURL.Path, "/") + "/status"
|
||||
statusURL.RawQuery = ""
|
||||
statusURL.Fragment = ""
|
||||
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodGet, statusURL.String(), nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create status request: %w", err)
|
||||
}
|
||||
request.Header.Set("Accept", "application/json")
|
||||
request.Header.Set("User-Agent", "shelly-exporter")
|
||||
if c.username != "" || c.password != "" {
|
||||
request.SetBasicAuth(c.username, c.password)
|
||||
}
|
||||
|
||||
response, err := c.httpClient.Do(request)
|
||||
if err != nil {
|
||||
return fmt.Errorf("request %s: %w", statusURL.String(), err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode < http.StatusOK || response.StatusCode >= http.StatusMultipleChoices {
|
||||
body, _ := io.ReadAll(io.LimitReader(response.Body, maxErrorBodySize))
|
||||
message := strings.TrimSpace(string(body))
|
||||
if message == "" {
|
||||
return fmt.Errorf("request %s returned %s", statusURL.String(), response.Status)
|
||||
}
|
||||
return fmt.Errorf("request %s returned %s: %s", statusURL.String(), response.Status, message)
|
||||
}
|
||||
|
||||
if err := json.NewDecoder(response.Body).Decode(destination); err != nil {
|
||||
return fmt.Errorf("decode response from %s: %w", statusURL.String(), err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package shelly
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestClientGetStatusUsesStatusEndpointAndBasicAuth(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
|
||||
if request.URL.Path != "/device/status" {
|
||||
t.Errorf("request path = %q, want /device/status", request.URL.Path)
|
||||
}
|
||||
username, password, ok := request.BasicAuth()
|
||||
if !ok || username != "admin" || password != "secret" {
|
||||
t.Errorf("BasicAuth() = (%q, %q, %t), want admin, secret, true", username, password, ok)
|
||||
}
|
||||
response.Header().Set("Content-Type", "application/json")
|
||||
_, _ = response.Write([]byte(`{"serial":42}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
client, err := NewClient(server.URL+"/device/", "admin", "secret", time.Second)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var status struct {
|
||||
Serial int `json:"serial"`
|
||||
}
|
||||
if err := client.GetStatus(context.Background(), &status); err != nil {
|
||||
t.Fatalf("GetStatus() returned an unexpected error: %v", err)
|
||||
}
|
||||
if status.Serial != 42 {
|
||||
t.Fatalf("Serial = %d, want 42", status.Serial)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientGetStatusReportsHTTPError(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(response http.ResponseWriter, _ *http.Request) {
|
||||
http.Error(response, "not authorized", http.StatusUnauthorized)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
client, err := NewClient(server.URL, "admin", "wrong", time.Second)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
err = client.GetStatus(context.Background(), &struct{}{})
|
||||
if err == nil || !strings.Contains(err.Error(), "401 Unauthorized") {
|
||||
t.Fatalf("GetStatus() error = %v, want a 401 error", err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user