-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexecuteremotely.go
More file actions
70 lines (61 loc) · 1.64 KB
/
executeremotely.go
File metadata and controls
70 lines (61 loc) · 1.64 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
package rcom
import (
"bytes"
"context"
"encoding/gob"
"fmt"
"net/http"
)
// ExecuteRemotely executes a command on a remote rcom server via HTTP.
//
// The function:
// 1. Validates the command
// 2. Encodes the command using gob encoding
// 3. Sends an HTTP POST request to the server address
// 4. Receives and decodes the gob-encoded result
//
// Parameters:
// - ctx: Context for cancellation and timeout
// - addr: Full server address including scheme and port (e.g., "http://localhost:8080")
// - c: The command to execute
//
// Returns an error if:
// - Command validation fails
// - Network request fails
// - Server returns non-200 status (e.g., command not allowed)
// - Response decoding fails
//
// The server must be running ListenAndServe with the command allowed.
// The context is respected for request cancellation and timeout.
func ExecuteRemotely(ctx context.Context, addr string, c *Command) (result *Result, err error) {
log.Debug("ExecuteRemotely").
Str("addr", addr).
Str("command", c.Name).
Log()
err = c.Validate()
if err != nil {
return nil, err
}
buf := bytes.NewBuffer(nil)
err = gob.NewEncoder(buf).Encode(c)
if err != nil {
return nil, err
}
request, err := http.NewRequestWithContext(ctx, "POST", addr, buf)
if err != nil {
return nil, err
}
response, err := http.DefaultClient.Do(request)
if err != nil {
return nil, err
}
if response.StatusCode != http.StatusOK {
return nil, fmt.Errorf("rcom.Command: response status %s", response.Status)
}
defer response.Body.Close()
err = gob.NewDecoder(response.Body).Decode(&result)
if err != nil {
return nil, err
}
return result, nil
}