forked from Flix14/printer-spooler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
122 lines (99 loc) · 2.34 KB
/
main.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"regexp"
prt "github.com/alexbrainman/printer"
"github.com/gin-gonic/gin"
"github.com/joho/godotenv"
)
func main() {
err := godotenv.Load()
if err != nil {
panic(err)
}
r := gin.Default()
version := r.Group("/v1")
{
version.GET("/print", printPdf)
}
// dbExample()
err = r.Run(fmt.Sprintf(":%s", os.Getenv("PORT")))
if err != nil {
panic(err)
}
defer func() {
if err := recover(); err != nil {
log.Println("panic occurred:", err)
}
}()
}
func printPdf(c *gin.Context) {
var re = regexp.MustCompile(os.Getenv("PRINTER"))
printers, err := prt.ReadNames()
if err != nil {
panic(err)
}
fmt.Println("PRINTERS:")
fmt.Println(printers) //Imprime en consola los nombres de las impresoras disponibles
printer := ""
for _, p := range printers {
if re.MatchString(p) {
printer = p
}
}
if printer != "" {
log.Println("Printer found ", printer)
content, err := ioutil.ReadFile(os.Getenv("FILE"))
if err != nil {
panic(err)
}
printContent("raw", content)
} else {
log.Println("Printer not found")
}
}
func checkErr(err error) {
if err != nil {
panic(err)
}
}
func printContent(datatype string, content []byte) {
name, err := prt.Default() // Regresa el nombre de la impresora por default
checkErr(err)
fmt.Println(name)
p, err := prt.Open(name) // Abre la impresora y regresa su struct
checkErr(err)
err = p.StartDocument("test", datatype)
checkErr(err)
err = p.StartPage()
checkErr(err)
n, err := p.Write(content) //Enviar documento para impresión
checkErr(err)
fmt.Println("Número de bytes:", n)
err = p.EndPage()
checkErr(err)
err = p.EndDocument()
checkErr(err)
err = p.Close()
checkErr(err)
}
func Cors() gin.HandlerFunc {
return func(c *gin.Context) {
method := c.Request.Method
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token")
c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
c.Header("Access-Control-Allow-Credentials", "true")
//放行所有OPTIONS方法
if method == "OPTIONS" {
c.AbortWithStatus(http.StatusNoContent)
}
// 处理请求
c.Next()
}
}