-
Notifications
You must be signed in to change notification settings - Fork 180
/
context.go
762 lines (668 loc) · 20.4 KB
/
context.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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
package dotweb
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"golang.org/x/net/websocket"
"net"
"net/http"
"net/url"
"os"
"path/filepath"
"strconv"
"time"
"github.com/devfeel/dotweb/cache"
"github.com/devfeel/dotweb/core"
"github.com/devfeel/dotweb/session"
)
const (
defaultMemory = 32 << 20 // 32 MB
defaultHttpCode = http.StatusOK
// ItemKeyHandleStartTime itemkey name for request handler start time
ItemKeyHandleStartTime = "dotweb.HttpContext.StartTime"
// ItemKeyHandleDuration itemkey name for request handler time duration
ItemKeyHandleDuration = "dotweb.HttpContext.HandleDuration"
)
const (
innerKeyAddView = "inner_AddView"
)
type (
Context interface {
Context() context.Context
SetTimeoutContext(timeout time.Duration) context.Context
WithContext(runCtx context.Context)
HttpServer() *HttpServer
Response() *Response
Request() *Request
WebSocket() *WebSocket
HijackConn() *HijackConn
RouterNode() RouterNode
RouterParams() Params
Handler() HttpHandle
Tools() *Tools
AppItems() core.ConcurrenceMap
Cache() cache.Cache
Items() core.ConcurrenceMap
ConfigSet() core.ReadonlyMap
ViewData() core.ConcurrenceMap
SessionID() string
Session() (state *session.SessionState)
DestorySession() error
Hijack() (*HijackConn, error)
IsHijack() bool
IsWebSocket() bool
End()
IsEnd() bool
Redirect(code int, targetUrl string) error
QueryString(key string) string
QueryInt(key string) int
QueryInt64(key string) int64
FormValue(key string) string
PostFormValue(key string) string
File(file string) (err error)
Attachment(file string, name string) error
Inline(file string, name string) error
Bind(i interface{}) error
BindJsonBody(i interface{}) error
// Validate validates provided `i`. It is usually called after `Context#Bind()`.
Validate(i interface{}) error
GetRouterName(key string) string
RemoteIP() string
SetCookieValue(name, value string, maxAge int)
SetCookie(cookie *http.Cookie)
RemoveCookie(name string)
ReadCookieValue(name string) (string, error)
ReadCookie(name string) (*http.Cookie, error)
AddView(name ...string) []string
View(name string) error
ViewC(code int, name string) error
Write(code int, content []byte) (int, error)
WriteString(contents ...interface{}) error
WriteStringC(code int, contents ...interface{}) error
WriteHtml(contents ...interface{}) error
WriteHtmlC(code int, contents ...interface{}) error
WriteBlob(contentType string, b []byte) error
WriteBlobC(code int, contentType string, b []byte) error
WriteJson(i interface{}) error
WriteJsonC(code int, i interface{}) error
WriteJsonBlob(b []byte) error
WriteJsonBlobC(code int, b []byte) error
WriteJsonp(callback string, i interface{}) error
WriteJsonpBlob(callback string, b []byte) error
//inner func
getMiddlewareStep() string
setMiddlewareStep(step string)
release()
reset(res *Response, r *Request, server *HttpServer, node RouterNode, params Params, handler HttpHandle)
setSessionID(id string)
setRouterParams(params Params)
setRouterNode(node RouterNode)
setHandler(handler HttpHandle)
getCancel() context.CancelFunc
setCancel(cancel context.CancelFunc)
}
HttpContext struct {
context context.Context
// Reserved
cancel context.CancelFunc
middlewareStep string
request *Request
routerNode RouterNode
routerParams Params
response *Response
webSocket *WebSocket
hijackConn *HijackConn
isWebSocket bool
isHijack bool
isEnd bool // indicating whether the current process should be terminated
httpServer *HttpServer
sessionID string
innerItems core.ConcurrenceMap
items core.ConcurrenceMap
viewData core.ConcurrenceMap
handler HttpHandle
tools *Tools
}
WebSocket struct {
Conn *websocket.Conn
}
// hijack conn
HijackConn struct {
ReadWriter *bufio.ReadWriter
Conn net.Conn
header string
}
)
// defaultContextCreater return new HttpContex{}
func defaultContextCreater() Context {
return &HttpContext{}
}
//************* HttpContext public func **********************
// reset response attr
func (ctx *HttpContext) reset(res *Response, r *Request, server *HttpServer, node RouterNode, params Params, handler HttpHandle) {
ctx.request = r
ctx.response = res
ctx.routerNode = node
ctx.routerParams = params
ctx.isHijack = false
ctx.isWebSocket = false
ctx.httpServer = server
ctx.innerItems = nil
ctx.items = nil
ctx.isEnd = false
ctx.handler = handler
ctx.Items().Set(ItemKeyHandleStartTime, time.Now())
}
// release all field
func (ctx *HttpContext) release() {
ctx.request = nil
ctx.response = nil
ctx.middlewareStep = ""
ctx.routerNode = nil
ctx.routerParams = nil
ctx.webSocket = nil
ctx.hijackConn = nil
ctx.isHijack = false
ctx.isWebSocket = false
ctx.httpServer = nil
ctx.isEnd = false
ctx.innerItems = nil
ctx.items = nil
ctx.viewData = nil
ctx.sessionID = ""
ctx.handler = nil
ctx.Items().Remove(ItemKeyHandleStartTime)
ctx.Items().Remove(ItemKeyHandleDuration)
}
// Context return context.Context
func (ctx *HttpContext) Context() context.Context {
return ctx.context
}
// SetTimeoutContext set new Timeout Context
// set Context & cancle
// withvalue RequestID
func (ctx *HttpContext) SetTimeoutContext(timeout time.Duration) context.Context {
ctx.context, ctx.cancel = context.WithTimeout(context.Background(), timeout)
ctx.context = context.WithValue(ctx.context, "RequestID", ctx.Request().RequestID())
return ctx.context
}
// WithContext set Context with RequestID
func (ctx *HttpContext) WithContext(runCtx context.Context) {
if runCtx == nil {
panic("nil context")
}
ctx.context = runCtx
ctx.context = context.WithValue(ctx.context, "RequestID", ctx.Request().RequestID())
}
// HttpServer return HttpServer
func (ctx *HttpContext) HttpServer() *HttpServer {
return ctx.httpServer
}
func (ctx *HttpContext) Response() *Response {
return ctx.response
}
func (ctx *HttpContext) Request() *Request {
return ctx.request
}
func (ctx *HttpContext) RouterNode() RouterNode {
return ctx.routerNode
}
func (ctx *HttpContext) WebSocket() *WebSocket {
return ctx.webSocket
}
func (ctx *HttpContext) IsWebSocket() bool {
return ctx.isWebSocket
}
func (ctx *HttpContext) IsHijack() bool {
return ctx.isHijack
}
func (ctx *HttpContext) HijackConn() *HijackConn {
return ctx.hijackConn
}
func (ctx *HttpContext) RouterParams() Params {
return ctx.routerParams
}
func (ctx *HttpContext) Handler() HttpHandle {
return ctx.handler
}
func (ctx *HttpContext) SessionID() string {
return ctx.sessionID
}
// AppContext get application's global appcontext
// issue #3
func (ctx *HttpContext) AppItems() core.ConcurrenceMap {
if ctx.httpServer != nil {
return ctx.httpServer.DotApp.Items
} else {
return core.NewConcurrenceMap()
}
}
// Cache get application's global cache
func (ctx *HttpContext) Cache() cache.Cache {
return ctx.httpServer.DotApp.Cache()
}
// getInnerItems get request's inner item context
// lazy init when first use
func (ctx *HttpContext) getInnerItems() core.ConcurrenceMap {
if ctx.innerItems == nil {
ctx.innerItems = core.NewConcurrenceMap()
}
return ctx.innerItems
}
// Items get request's item context
// lazy init when first use
func (ctx *HttpContext) Items() core.ConcurrenceMap {
if ctx.items == nil {
ctx.items = core.NewConcurrenceMap()
}
return ctx.items
}
// Tools get tools
// lazy init when first use
func (ctx *HttpContext) Tools() *Tools {
if ctx.tools == nil {
ctx.tools = new(Tools)
}
return ctx.tools
}
// ConfigSet get appset from config file
// update for issue #16 Config file
func (ctx *HttpContext) ConfigSet() core.ReadonlyMap {
return ctx.HttpServer().DotApp.Config.ConfigSet
}
// ViewData get view data context
// lazy init when first use
func (ctx *HttpContext) ViewData() core.ConcurrenceMap {
if ctx.viewData == nil {
ctx.viewData = core.NewConcurrenceMap()
}
return ctx.viewData
}
// Session get session state in current context
func (ctx *HttpContext) Session() (state *session.SessionState) {
if ctx.httpServer == nil {
panic("no effective http-server")
}
if !ctx.httpServer.SessionConfig().EnabledSession {
panic("http-server not enabled session")
}
state, _ = ctx.httpServer.sessionManager.GetSessionState(ctx.sessionID)
return state
}
// DestorySession delete all contents of the session and set the sessionId to empty
func (ctx *HttpContext) DestorySession() error {
if ctx.httpServer != nil {
ctx.Session().Clear()
if err := ctx.HttpServer().sessionManager.RemoveSessionState(ctx.SessionID()); err != nil {
return err
}
ctx.sessionID = ""
ctx.SetCookieValue(session.DefaultSessionCookieName, "", -1)
}
return nil
}
// Hijack make current connection to hijack mode
func (ctx *HttpContext) Hijack() (*HijackConn, error) {
hj, ok := ctx.response.Writer().(http.Hijacker)
if !ok {
return nil, errors.New("The Web Server does not support Hijacking! ")
}
conn, bufrw, err := hj.Hijack()
if err != nil {
return nil, errors.New("Hijack error:" + err.Error())
}
ctx.hijackConn = &HijackConn{Conn: conn, ReadWriter: bufrw, header: "HTTP/1.1 200 OK\r\n"}
ctx.isHijack = true
return ctx.hijackConn, nil
}
// End set context user handler process end
// if set HttpContext.End,ignore user handler, but exec all http module - fixed issue #5
func (ctx *HttpContext) End() {
ctx.isEnd = true
}
func (ctx *HttpContext) IsEnd() bool {
return ctx.isEnd
}
// Redirect replies to the request with a redirect to url and with httpcode
// default you can use http.StatusFound
func (ctx *HttpContext) Redirect(code int, targetUrl string) error {
return ctx.response.Redirect(code, targetUrl)
}
// QueryString returns request parameters according to key
func (ctx *HttpContext) QueryString(key string) string {
return ctx.request.QueryString(key)
}
// QueryInt get query key with int format
// if not exists or not int type, return 0
func (ctx *HttpContext) QueryInt(key string) int {
param := ctx.request.QueryString(key)
if param == "" {
return 0
}
val, err := strconv.Atoi(param)
if err != nil {
return 0
}
return val
}
// QueryInt64 get query key with int64 format
// if not exists or not int64 type, return 0
func (ctx *HttpContext) QueryInt64(key string) int64 {
param := ctx.request.QueryString(key)
if param == "" {
return 0
}
val, err := strconv.ParseInt(param, 10, 64)
if err != nil {
return 0
}
return val
}
// FormValue returns the first value for the named component of the query.
// POST and PUT body parameters take precedence over URL query string values.
func (ctx *HttpContext) FormValue(key string) string {
return ctx.request.FormValue(key)
}
// PostFormValue returns the first value for the named component of the POST,
// PATCH, or PUT request body. URL query parameters are ignored.
func (ctx *HttpContext) PostFormValue(key string) string {
return ctx.request.PostFormValue(key)
}
// File sends a response with the content of the file
// if file not exists, response 404
// for issue #39
func (ctx *HttpContext) File(file string) (err error) {
f, err := os.Open(file)
if err != nil {
HTTPNotFound(ctx)
return nil
}
defer f.Close()
fi, _ := f.Stat()
if fi.IsDir() {
file = filepath.Join(file, ctx.HttpServer().IndexPage())
f, err = os.Open(file)
if err != nil {
HTTPNotFound(ctx)
return nil
}
defer f.Close()
if fi, err = f.Stat(); err != nil {
return err
}
}
http.ServeContent(ctx.Response().Writer(), ctx.Request().Request, fi.Name(), fi.ModTime(), f)
return nil
}
// Attachment sends a response as attachment, prompting client to save the file.
// for issue #39
func (ctx *HttpContext) Attachment(file, name string) (err error) {
return ctx.contentDisposition(file, name, "attachment")
}
// Inline sends a response as inline, opening the file in the browser.
// if file not exists, response 404
// for issue #39
func (ctx *HttpContext) Inline(file, name string) (err error) {
return ctx.contentDisposition(file, name, "inline")
}
// contentDisposition set Content-disposition and response file
func (ctx *HttpContext) contentDisposition(file, name, dispositionType string) (err error) {
ctx.Response().SetHeader(HeaderContentDisposition, fmt.Sprintf("%s; filename=%s", dispositionType, name))
ctx.File(file)
return
}
// Bind decode req.Body or form-value to struct
func (ctx *HttpContext) Bind(i interface{}) error {
return ctx.httpServer.Binder().Bind(i, ctx)
}
// BindJsonBody default use json decode req.Body to struct
func (ctx *HttpContext) BindJsonBody(i interface{}) error {
return ctx.httpServer.Binder().BindJsonBody(i, ctx)
}
// Validate validates data with HttpServer::Validator
// We will implementing inner validator on next version
func (ctx *HttpContext) Validate(i interface{}) error {
if ctx.httpServer.Validator == nil {
return ErrValidatorNotRegistered
}
return ctx.httpServer.Validator.Validate(i)
}
// GetRouterName get router name
func (ctx *HttpContext) GetRouterName(key string) string {
return ctx.routerParams.ByName(key)
}
// RemoteIP return user IP address
func (ctx *HttpContext) RemoteIP() string {
return ctx.request.RemoteIP()
}
// SetCookieValue write cookie for name & value & maxAge
// default path = "/"
// default domain = current domain
// default maxAge = 0 // seconds
// seconds=0 means no 'Max-Age' attribute specified.
// seconds<0 means delete cookie now, equivalently 'Max-Age: 0'
// seconds>0 means Max-Age attribute present and given in seconds
func (ctx *HttpContext) SetCookieValue(name, value string, maxAge int) {
cookie := &http.Cookie{Name: name, Value: url.QueryEscape(value), MaxAge: maxAge}
cookie.Path = "/"
ctx.SetCookie(cookie)
}
// SetCookie write cookie with cookie-obj
func (ctx *HttpContext) SetCookie(cookie *http.Cookie) {
http.SetCookie(ctx.response.Writer(), cookie)
}
// RemoveCookie remove cookie for path&name
func (ctx *HttpContext) RemoveCookie(name string) {
cookie := &http.Cookie{Name: name, MaxAge: -1}
ctx.SetCookie(cookie)
}
// ReadCookieValue read cookie value for name
func (ctx *HttpContext) ReadCookieValue(name string) (string, error) {
cookieobj, err := ctx.request.Cookie(name)
if err != nil {
return "", err
} else {
return url.QueryUnescape(cookieobj.Value)
}
}
// ReadCookie read cookie object for name
func (ctx *HttpContext) ReadCookie(name string) (*http.Cookie, error) {
return ctx.request.Cookie(name)
}
// AddView add need parse views before View()
func (ctx *HttpContext) AddView(names ...string) []string {
var views []string
item, exists := ctx.getInnerItems().Get(innerKeyAddView)
if exists {
views = item.([]string)
}
views = append(views, names...)
ctx.getInnerItems().Set(innerKeyAddView, views)
return views
}
// View write view content to response
func (ctx *HttpContext) View(name string) error {
return ctx.ViewC(defaultHttpCode, name)
}
// ViewC write (httpCode, view content) to response
func (ctx *HttpContext) ViewC(code int, name string) error {
ctx.response.SetStatusCode(code)
ctx.AddView(name)
var views []string
item, exists := ctx.getInnerItems().Get(innerKeyAddView)
if exists {
views = item.([]string)
} else {
return errors.New("get view info error")
}
err := ctx.httpServer.Renderer().Render(ctx.response.Writer(), ctx.ViewData().GetCurrentMap(), ctx, views...)
return err
}
// Write write code and content content to response
func (ctx *HttpContext) Write(code int, content []byte) (int, error) {
if ctx.IsHijack() {
// TODO:hijack mode, status-code set default 200
return ctx.hijackConn.WriteBlob(content)
} else {
return ctx.response.Write(code, content)
}
}
// WriteString write (200, string, text/plain) to response
func (ctx *HttpContext) WriteString(contents ...interface{}) error {
return ctx.WriteStringC(defaultHttpCode, contents...)
}
// WriteStringC write (httpCode, string, text/plain) to response
func (ctx *HttpContext) WriteStringC(code int, contents ...interface{}) error {
content := fmt.Sprint(contents...)
return ctx.WriteBlobC(code, MIMETextPlainCharsetUTF8, []byte(content))
}
// WriteString write (200, string, text/html) to response
func (ctx *HttpContext) WriteHtml(contents ...interface{}) error {
return ctx.WriteHtmlC(defaultHttpCode, contents...)
}
// WriteHtmlC write (httpCode, string, text/html) to response
func (ctx *HttpContext) WriteHtmlC(code int, contents ...interface{}) error {
content := fmt.Sprint(contents...)
return ctx.WriteBlobC(code, MIMETextHTMLCharsetUTF8, []byte(content))
}
// WriteBlob write []byte content to response
func (ctx *HttpContext) WriteBlob(contentType string, b []byte) error {
return ctx.WriteBlobC(defaultHttpCode, contentType, b)
}
// WriteBlobC write (httpCode, []byte) to response
func (ctx *HttpContext) WriteBlobC(code int, contentType string, b []byte) error {
if contentType != "" {
ctx.response.SetContentType(contentType)
}
if ctx.IsHijack() {
_, err := ctx.hijackConn.WriteBlob(b)
return err
} else {
_, err := ctx.response.Write(code, b)
return err
}
}
// WriteJson write (httpCode, json string) to response
// auto convert interface{} to json string
func (ctx *HttpContext) WriteJson(i interface{}) error {
return ctx.WriteJsonC(defaultHttpCode, i)
}
// WriteJsonC write (httpCode, json string) to response
// auto convert interface{} to json string
func (ctx *HttpContext) WriteJsonC(code int, i interface{}) error {
b, err := json.Marshal(i)
if err != nil {
return err
}
return ctx.WriteJsonBlobC(code, b)
}
// WriteJsonBlob write json []byte to response
func (ctx *HttpContext) WriteJsonBlob(b []byte) error {
return ctx.WriteJsonBlobC(defaultHttpCode, b)
}
// WriteJsonBlobC write (httpCode, json []byte) to response
func (ctx *HttpContext) WriteJsonBlobC(code int, b []byte) error {
return ctx.WriteBlobC(code, MIMEApplicationJSONCharsetUTF8, b)
}
// WriteJsonp write jsonp string to response
func (ctx *HttpContext) WriteJsonp(callback string, i interface{}) error {
b, err := json.Marshal(i)
if err != nil {
return err
}
return ctx.WriteJsonpBlob(callback, b)
}
// WriteJsonpBlob write jsonp string as []byte to response
func (ctx *HttpContext) WriteJsonpBlob(callback string, b []byte) error {
var err error
ctx.response.SetContentType(MIMEApplicationJavaScriptCharsetUTF8)
// For jihack context, write header first
if ctx.IsHijack() {
if _, err = ctx.hijackConn.WriteBlob([]byte(ctx.hijackConn.header + "\r\n")); err != nil {
return err
}
}
if err = ctx.WriteBlob("", []byte(callback+"(")); err != nil {
return err
}
if err = ctx.WriteBlob("", b); err != nil {
return err
}
err = ctx.WriteBlob("", []byte(");"))
return err
}
//**************** HttpContext inner func ************************
// setMiddlewareStep
func (ctx *HttpContext) setMiddlewareStep(step string) {
ctx.middlewareStep = step
}
// getMiddlewareStep
func (ctx *HttpContext) getMiddlewareStep() string {
return ctx.middlewareStep
}
// setSessionID
func (ctx *HttpContext) setSessionID(id string) {
ctx.sessionID = id
}
// setRouterParams
func (ctx *HttpContext) setRouterParams(params Params) {
ctx.routerParams = params
}
// setRouterNode
func (ctx *HttpContext) setRouterNode(node RouterNode) {
ctx.routerNode = node
}
// setHandler
func (ctx *HttpContext) setHandler(handler HttpHandle) {
ctx.handler = handler
}
// getCancel return context.CancelFunc
func (ctx *HttpContext) getCancel() context.CancelFunc {
return ctx.cancel
}
// setCancel
func (ctx *HttpContext) setCancel(cancel context.CancelFunc) {
ctx.cancel = cancel
}
//************* WebSocket public func **********************
// Request get http request
func (ws *WebSocket) Request() *http.Request {
return ws.Conn.Request()
}
// SendMessage send message from websocket.conn
func (ws *WebSocket) SendMessage(msg string) error {
return websocket.Message.Send(ws.Conn, msg)
}
// ReadMessage read message from websocket.conn
func (ws *WebSocket) ReadMessage() (string, error) {
str := ""
err := websocket.Message.Receive(ws.Conn, &str)
return str, err
}
//************* HijackConn public func **********************
// WriteString hjiack conn write string
func (hj *HijackConn) WriteString(content string) (int, error) {
n, err := hj.ReadWriter.WriteString(hj.header + "\r\n" + content)
if err == nil {
hj.ReadWriter.Flush()
}
return n, err
}
// WriteBlob hjiack conn write []byte
func (hj *HijackConn) WriteBlob(p []byte) (size int, err error) {
size, err = hj.ReadWriter.Write(p)
if err == nil {
hj.ReadWriter.Flush()
}
return
}
// SetHeader hjiack conn write header
func (hj *HijackConn) SetHeader(key, value string) {
hj.header += key + ": " + value + "\r\n"
}
// Close close hijack conn
func (hj *HijackConn) Close() error {
return hj.Conn.Close()
}