-
Notifications
You must be signed in to change notification settings - Fork 4
/
printserver.go
444 lines (349 loc) · 7.25 KB
/
printserver.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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
/*
*
* Project printServer, an api rest responsible for printing to a Zebra thermal printer.
* The printServer will receive a cryptographic POST containing
* the Zpl content so that the printer can print.
*
* @package main
* @author @jeffotoni
* @size 28/07/2017
*
*/
package main
//
//
//
import (
"encoding/json"
"fmt"
"github.com/codegangsta/negroni"
"github.com/didip/tollbooth"
authjwt "github.com/jeffotoni/printserver/authentication"
"log"
"net/http"
"os"
"os/exec"
// "reflect"
"time"
)
//
//
//
const (
HttpHeaderTitle = `PrintServer`
HttpHeaderMsg = `Good Server, thank you.`
NewLimiter = 250
SizeByteAllowed = 1 << 23
HandlerToken = "/token"
HandlerV1Print = "/print"
HandlerPing = "/ping"
)
//
//
//
var (
err error
returns string
confServer *http.Server
)
//''
// Structure of our server configurations
//
type Configs struct {
Domain string `json:"domain"`
Process string `json:"process"`
Ping string `json:"ping"`
ServerPort string `json:"serverport"`
Host string `json:"host"`
Schema string `json:"shcema"`
ServerHost string `json:"serverhost"`
}
// This method Message is to return our messages
// in json, ie the client will
// receive messages in json format
type Message struct {
Code int `json:code`
Msg string `json:msg`
}
//
// Type responsible for defining a function that returns boolean
//
type fn func(w http.ResponseWriter, r *http.Request) bool
//
// This method ConfigJson sets up our
// server variables from our struct
//
func ConfigJson() string {
// Defining the values of our config
data := &Configs{Domain: "localhost", Process: "2", Ping: "ok", ServerPort: "9001", Host: "", Schema: "http", ServerHost: "localhost"}
// Converting our struct into json format
cjson, err := json.Marshal(data)
if err != nil {
// handle err
}
return string(cjson)
}
// This method Config returns the objects
// of our config so that it can be accessed
func Config() *Configs {
var objason Configs
jsonT := []byte(ConfigJson())
json.Unmarshal(jsonT, &objason)
return &objason
}
//
// This function already contains the method that does
// the validation of the token, only receives a parameter
// that is the handler to be executed if token is true
//
func HandlerAuth(handler http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
//if auth(w, r) {
if authjwt.HandlerValidate(w, r) {
handler(w, r)
}
}
}
//
// Function responsible for abstraction and receive the
// authentication function and the handler that will execute if it is true
//
func HandlerFuncAuth(auth fn, handler http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if auth(w, r) {
handler(w, r)
}
}
}
//
//
//
func check(e error) {
if e != nil {
panic(e)
}
}
//
// Mounting the properties on the api screen
//
func ShowScreen(cfg *Configs) {
//
// Basic Authentication
//
oauthToken := cfg.Schema + "://" + cfg.ServerHost + ":" + cfg.ServerPort + HandlerToken
//
//
//
ping := cfg.Schema + "://" + cfg.ServerHost + ":" + cfg.ServerPort + HandlerPing
//
//
//
printer := cfg.Schema + "://" + cfg.ServerHost + ":" + cfg.ServerPort + HandlerV1Print
//
//
//
sizeMb := (SizeByteAllowed / 1024) / 1024
//
// Showing on the screen
//
fmt.Println("Start port:", cfg.ServerPort)
fmt.Println("Endpoints:")
fmt.Println(oauthToken)
fmt.Println(ping)
fmt.Println(printer)
fmt.Println("Max bytes:", sizeMb, "Mb")
//
// Maximum NewLimiter requests per second per client. Additional requests result in a HTTP 429 (Too Many Requests) error.
//
fmt.Println("Requests ", NewLimiter, "per 1 second")
}
//
// Testing whether the service is online
//
func Ping(w http.ResponseWriter, r *http.Request) {
//
//
//
json := `{"msg":"pong"}`
//
//
//
pong := []byte(json)
//
//
//
w.Header().Set(HttpHeaderTitle, HttpHeaderMsg)
//
//
//
w.Header().Set("X-Custom-Header", "HeaderValue-x83838374774")
//
//
//
w.Header().Set("Content-Type", "application/json")
//
//
//
w.WriteHeader(http.StatusOK)
//
//
//
w.Write(pong)
}
//
// Zebra printer, the printer is networked, or the local
// machine is connected to the printer.
// The program will send a file to printer
//
func Print(w http.ResponseWriter, req *http.Request) {
//
//
//
var json_msg string
//
//
//
var HttpMsgHeader int
//
//
//
if req.Method == "POST" {
//
//
//
ZPL := req.FormValue("zpl")
//
//
//
CODE := req.FormValue("code")
if len(CODE) == 0 || len(ZPL) == 0 {
json_msg = `{"msg":"error No Content!"}`
HttpMsgHeader = http.StatusBadRequest
} else {
HttpMsgHeader = http.StatusOK
//
//
//
PathZpl := "/tmp/" + CODE + ".zpl"
//
// Generate a .zpl file
//
ZplByte := []byte(ZPL)
//
//
//
f, err := os.Create(PathZpl)
//
//
check(err)
//
//
//
defer f.Close()
//
//
//
size, errx := f.Write(ZplByte)
//
//
//
// err = ioutil.WriteFile(PathZpl, ZplByte, 0754)
check(errx)
//
//
//
// command := "lpr -P zebra -o raw "
//
// To print zpl on zebra printer in linux terminal
//
out, errc := exec.Command("lpr", "-P", "zebra", "-o", "raw", PathZpl).Output()
if errc != nil {
// log.Fatal(errc)
fmt.Println(errc)
}
//
//
//
fmt.Printf("Running command%s\n", out)
//
//
//
json_msg = `{"msg":"Printing performed successfully","bytes":"` + fmt.Sprintf("%d", size) + `"}`
}
} else {
//
//
//
json_msg = `{"msg":"Error Only accepts POST"}`
}
//
//
//
json := []byte(json_msg)
//
//
//
w.Header().Set(HttpHeaderTitle, HttpHeaderMsg)
//
//
//
w.Header().Set("X-Custom-Header", "HeaderValue-x83838374774")
//
//
//
w.Header().Set("Content-Type", "application/json")
//
//
//
w.WriteHeader(HttpMsgHeader)
//
//
//
w.Write(json)
}
//
// start
//
func main() {
//
//
//
cfg := Config()
//
//
//
ShowScreen(cfg)
// Creating limiter for all handlers
// or one for each handler. Your choice.
// This limiter basically says: allow at most NewLimiter request per 1 second.
limiter := tollbooth.NewLimiter(NewLimiter, time.Second)
// Limit only GET and POST requests.
limiter.Methods = []string{"GET", "POST"}
//
//
//
mux := http.NewServeMux()
// We had problem in doing method authentication and limit rate using negroni
// mux.Handle("/ping", negroni.New(negroni.HandlerFunc(MyMiddlewareauthjwt), negroni.HandlerFunc(MyMiddlewarePing)))
mux.Handle(HandlerPing, tollbooth.LimitFuncHandler(limiter, HandlerFuncAuth(authjwt.HandlerValidate, Ping)))
mux.Handle(HandlerV1Print, tollbooth.LimitFuncHandler(limiter, HandlerAuth(Print)))
//
// Off the default mux
// Does not need authentication, only user key and token
//
mux.Handle(HandlerToken, tollbooth.LimitFuncHandler(limiter, authjwt.LoginBasic))
// mux.Handle("/validate", tollbooth.LimitFuncHandler(limiter, authjwt.ValidateToken))
nClassic := negroni.Classic()
nClassic.UseHandler(mux)
//
//
//
confServer = &http.Server{
Addr: ":" + cfg.ServerPort,
Handler: nClassic,
//ReadTimeout: 30 * time.Second,
//WriteTimeout: 20 * time.Second,
MaxHeaderBytes: 1 << 23, // Size accepted by package
}
log.Fatal(confServer.ListenAndServe())
}