-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsend.go
More file actions
85 lines (73 loc) · 1.87 KB
/
send.go
File metadata and controls
85 lines (73 loc) · 1.87 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
85
package main
import (
"bytes"
"context"
"fmt"
"io"
"log"
"mime/multipart"
"net/http"
"os"
"path/filepath"
"time"
"github.com/urfave/cli/v3"
)
func SendAction(con context.Context, cmd *cli.Command) error {
fileba, err := os.ReadFile(cmd.StringArg("file"))
if err == os.ErrNotExist {
fmt.Println("error: file provided does not exist.")
return err
} else if err != nil {
fmt.Println("error: could not read provided file.")
return err
}
var body bytes.Buffer
form := multipart.NewWriter(&body)
name := filepath.Base(cmd.StringArg("file"))
fw, err := form.CreateFormFile("file", name)
if err != nil {
fmt.Println("error: could not add file to form.")
return err
}
_, werr := fw.Write(fileba)
if werr != nil {
fmt.Println("error: could not write file to form.")
return err
}
cerr := form.Close()
if cerr != nil {
fmt.Println("error: could not close to form.")
return err
}
transferreq, err := http.NewRequest("POST", "http://"+cmd.StringArg("printer")+"/upload/"+name, &body)
if err != nil {
fmt.Println("error: could not create request")
return err
}
transferreq.Header.Add("Content-Type", form.FormDataContentType())
resp, err := http.DefaultClient.Do(transferreq)
if err != nil {
fmt.Println("error: could not send request:", err)
return err
}
if resp.StatusCode != 200 {
ba, _ := io.ReadAll(resp.Body)
fmt.Println("error: printer reported http error:", string(ba))
return err
}
fmt.Println(Success+"File has been transferred to the printer with the name", name)
if cmd.Bool("print") {
time.Sleep(3 * time.Second)
pws, err := NewPrinterWebsocket(cmd.StringArg("printer"))
if err != nil {
fmt.Println("error: printer reported ws error:", err)
return err
}
err = pws.ModifyFile(name, "print")
if err != nil {
log.Fatal("failed printing uploaded file:", err)
}
fmt.Println("print has been started")
}
return nil
}