/
printer.go
62 lines (53 loc) · 1.25 KB
/
printer.go
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
package printer
import (
"net/http"
"net/http/cookiejar"
"time"
)
// printer is a struct to interact with a remote Brother printer
type printer struct {
httpClient *http.Client
baseUrl string
userAgent string
}
// PrinterConfig contains the information necessary to create a printer
// type which interfaces with a remote Brother printer
type Config struct {
Hostname string
Password string
UserAgent string
UseHttp bool
}
// NewPrinter creates a new printer from a PrinterConfig
func NewPrinter(cfg Config) (*printer, error) {
baseUrl := "https://" + cfg.Hostname
// http instead?
if cfg.UseHttp {
baseUrl = "http://" + cfg.Hostname
}
// make cookie jar
jar, err := cookiejar.New(nil)
if err != nil {
return nil, err
}
p := &printer{
httpClient: &http.Client{
// disable redirect (POSTs return 301 and if client follows it loses the post response)
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
Jar: jar,
// set client timeout
Timeout: 30 * time.Second,
Transport: http.DefaultTransport,
},
baseUrl: baseUrl,
userAgent: cfg.UserAgent,
}
// login & get cookie
err = p.login(cfg.Password)
if err != nil {
return nil, err
}
return p, nil
}