-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinux.go
More file actions
84 lines (72 loc) · 2.13 KB
/
linux.go
File metadata and controls
84 lines (72 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
//go:build linux
// +build linux
package PluginLib
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"time"
)
const socketPath = "./SSUI/plugins/sockets/ssui.sock"
// Get sends a GET request to the specified SSUI endpoint and unmarshals the JSON response into the provided response interface.
func Get(endpoint string, response any) (any, error) {
transport := &http.Transport{
DialContext: func(_ context.Context, _, _ string) (net.Conn, error) {
return net.Dial("unix", socketPath)
},
}
client := &http.Client{
Transport: transport,
Timeout: 10 * time.Second,
}
resp, err := client.Get("http://localhost" + endpoint)
if err != nil {
return nil, fmt.Errorf("failed to send GET request to %s: %w", endpoint, err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response body: %w", err)
}
if response != nil {
if err := json.Unmarshal(body, response); err != nil {
return nil, fmt.Errorf("failed to unmarshal JSON response: %w", err)
}
}
return response, nil
}
// Post sends a POST request to the specified SSUI endpoint with the given payload and unmarshals the JSON response.
func Post(endpoint string, payload any, response any) (any, error) {
transport := &http.Transport{
DialContext: func(_ context.Context, _, _ string) (net.Conn, error) {
return net.Dial("unix", socketPath)
},
}
client := &http.Client{
Transport: transport,
Timeout: 10 * time.Second,
}
body, err := json.Marshal(payload)
if err != nil {
return nil, fmt.Errorf("failed to marshal payload: %w", err)
}
resp, err := client.Post("http://localhost"+endpoint, "application/json", bytes.NewReader(body))
if err != nil {
return nil, fmt.Errorf("failed to send POST request to %s: %w", endpoint, err)
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response body: %w", err)
}
if response != nil {
if err := json.Unmarshal(respBody, response); err != nil {
return nil, fmt.Errorf("failed to unmarshal JSON response: %w", err)
}
}
return response, nil
}