aboutsummaryrefslogtreecommitdiffstats
path: root/lib/ipc/send.go
blob: 522e944a840deacbab009a3a5143a421c41f4707 (plain) (blame)
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
package ipc

import (
	"bufio"
	"errors"
	"fmt"
	"net"
	"path"

	"github.com/kyoh86/xdg"
)

func ConnectAndExec(args []string) error {
	sockpath := path.Join(xdg.RuntimeDir(), "aerc.sock")
	conn, err := net.Dial("unix", sockpath)
	if err != nil {
		return err
	}
	defer conn.Close()

	req, err := (&Request{Arguments: args}).Encode()
	if err != nil {
		return fmt.Errorf("failed to encode request: %w", err)
	}

	_, err = conn.Write(append(req, '\n'))
	if err != nil {
		return fmt.Errorf("failed to send message: %w", err)
	}
	scanner := bufio.NewScanner(conn)
	if !scanner.Scan() {
		return errors.New("No response from server")
	}
	resp, err := DecodeResponse(scanner.Bytes())
	if err != nil {
		return err
	}

	// TODO: handle this in a more elegant manner
	if resp.Error == "" {
		fmt.Println("result: success")
	} else {
		fmt.Println("result: ", resp.Error)
	}

	return nil
}