forked from go-aah/aah
-
Notifications
You must be signed in to change notification settings - Fork 0
/
aah_test.go
723 lines (625 loc) · 20.8 KB
/
aah_test.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
// Copyright (c) Jeevanandam M. (https://github.com/jeevatkm)
// Source code and usage is governed by a MIT style
// license that can be found in the LICENSE file.
package aah
import (
"bytes"
"compress/gzip"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path"
"path/filepath"
"reflect"
"strings"
"testing"
"time"
"aahframe.work/ahttp"
"aahframe.work/ainsp"
"aahframe.work/config"
"aahframe.work/console"
ess "aahframe.work/essentials"
"aahframe.work/log"
"github.com/stretchr/testify/assert"
)
func TestAahApp(t *testing.T) {
importPath := filepath.Join(testdataBaseDir(), "webapp1")
ts := newTestServer(t, importPath)
defer ts.Close()
t.Logf("Test Server URL: %s", ts.URL)
// Do not follow redirect
if http.DefaultClient.CheckRedirect == nil {
http.DefaultClient.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
}
}
// GET - /index.html or /
t.Log("GET - /index.html or /")
req, err := http.NewRequest(ahttp.MethodGet, ts.URL+"?lang=en", nil)
assert.Nil(t, err)
req.Header.Add(ahttp.HeaderAcceptEncoding, "gzip, deflate, sdch, br")
result := fireRequest(t, req)
assert.Equal(t, 200, result.StatusCode)
assert.NotNil(t, result.Header)
assert.Equal(t, "text/html; charset=utf-8", result.Header.Get(ahttp.HeaderContentType))
assert.Equal(t, "SAMEORIGIN", result.Header.Get(ahttp.HeaderXFrameOptions))
assert.Equal(t, "nosniff", result.Header.Get(ahttp.HeaderXContentTypeOptions))
assert.Equal(t, "Before Called successfully", result.Header.Get("X-Before-Interceptor"))
assert.Equal(t, "After Called successfully", result.Header.Get("X-After-Interceptor"))
assert.Equal(t, "Finally Called successfully", result.Header.Get("X-Finally-Interceptor"))
assert.True(t, strings.Contains(result.Body, "Test Application webapp1 Yes it works!!!"))
assert.True(t, strings.Contains(result.Body, "aah framework web application"))
// GET - /get-text.html
t.Log("GET - /get-text.html")
req, err = http.NewRequest(ahttp.MethodGet, ts.URL+"/get-text.html", nil)
assert.Nil(t, err)
req.Header.Add(ahttp.HeaderAcceptEncoding, "gzip, deflate, sdch, br")
result = fireRequest(t, req)
assert.Equal(t, 200, result.StatusCode)
assert.NotNil(t, result.Header)
assert.Equal(t, "SAMEORIGIN", result.Header.Get(ahttp.HeaderXFrameOptions))
assert.Equal(t, "nosniff", result.Header.Get(ahttp.HeaderXContentTypeOptions))
assert.Equal(t, "BeforeText Called successfully", result.Header.Get("X-Beforetext-Interceptor"))
assert.Equal(t, "AfterText Called successfully", result.Header.Get("X-Aftertext-Interceptor"))
assert.Equal(t, "FinallyText Called successfully", result.Header.Get("X-Finallytext-Interceptor"))
assert.True(t, strings.Contains(result.Body, "This is text render response"))
// Redirect - /test-redirect.html
t.Log("Redirect - /test-redirect.html")
req, err = http.NewRequest(ahttp.MethodGet, ts.URL+"/test-redirect.html", nil)
assert.Nil(t, err)
result = fireRequest(t, req)
assert.Equal(t, 302, result.StatusCode)
assert.NotNil(t, result.Header)
assert.True(t, result.Header.Get(ahttp.HeaderLocation) != "")
assert.True(t, strings.Contains(result.Body, "Found"))
// Redirect - /test-redirect.html?mode=text_get
t.Log("Redirect - /test-redirect.html?mode=text_get")
req, err = http.NewRequest(ahttp.MethodGet, ts.URL+"/test-redirect.html?mode=text_get", nil)
assert.Nil(t, err)
result = fireRequest(t, req)
assert.Equal(t, 302, result.StatusCode)
assert.NotNil(t, result.Header)
hdrLocation := result.Header.Get(ahttp.HeaderLocation)
assert.True(t, hdrLocation != "")
assert.True(t, strings.Contains(hdrLocation, "Param2"))
assert.True(t, strings.Contains(result.Body, "Found"))
// Redirect - /test-redirect.html?mode=status
t.Log("Redirect - /test-redirect.html?mode=status")
req, err = http.NewRequest(ahttp.MethodGet, ts.URL+"/test-redirect.html?mode=status", nil)
assert.Nil(t, err)
result = fireRequest(t, req)
assert.Equal(t, 307, result.StatusCode)
assert.NotNil(t, result.Header)
assert.True(t, result.Header.Get(ahttp.HeaderLocation) != "")
assert.True(t, strings.Contains(result.Body, "Temporary Redirect"))
// Form Submit - /form-submit - Anti-CSRF nicely guarded the form request :)
t.Log("Form Submit - /form-submit - Anti-CSRF nicely guarded the form request :)")
form := url.Values{}
form.Add("id", "1000001")
form.Add("product_name", "Test Product")
form.Add("username", "welcome")
form.Add("email", "[email protected]")
req, err = http.NewRequest(ahttp.MethodPost, ts.URL+"/form-submit", strings.NewReader(form.Encode()))
assert.Nil(t, err)
req.Header.Set(ahttp.HeaderContentType, ahttp.ContentTypeForm.String())
result = fireRequest(t, req)
assert.Equal(t, 403, result.StatusCode)
assert.NotNil(t, result.Header)
assert.True(t, strings.Contains(result.Body, "403 Forbidden"))
// Form Submit - /form-submit with anti_csrf_token
t.Log("Form Submit - /form-submit with anti_csrf_token")
secret := ts.app.SecurityManager().AntiCSRF.GenerateSecret()
secretstr := ts.app.SecurityManager().AntiCSRF.SaltCipherSecret(secret)
form.Add("anti_csrf_token", secretstr)
wt := httptest.NewRecorder()
err = ts.app.SecurityManager().AntiCSRF.SetCookie(wt, secret)
assert.Nil(t, err)
cookieValue := wt.Header().Get("Set-Cookie")
req, err = http.NewRequest(ahttp.MethodPost, ts.URL+"/form-submit", strings.NewReader(form.Encode()))
assert.Nil(t, err)
req.Header.Set(ahttp.HeaderContentType, ahttp.ContentTypeForm.String())
req.Header.Set(ahttp.HeaderCookie, cookieValue)
result = fireRequest(t, req)
assert.Equal(t, 200, result.StatusCode)
assert.True(t, strings.Contains(result.Body, "Data recevied successfully"))
assert.True(t, strings.Contains(result.Body, "[email protected]"))
assert.True(t, strings.Contains(strings.Join(result.Header["Set-Cookie"], "||"), "aah_session="))
// CreateRecord - /create-record - JSON post request
// This is webapp test app, send request with anti_csrf_token on HTTP header
t.Log("CreateRecord - /create-record - JSON post request\n" +
"This is webapp test app, send request with anti_csrf_token on HTTP header")
jsonStr := `{
"first_name":"My firstname",
"last_name": "My lastname",
"email": "[email protected]",
"number": 8253645635463
}`
req, err = http.NewRequest(ahttp.MethodPost, ts.URL+"/create-record", strings.NewReader(jsonStr))
assert.Nil(t, err)
req.Header.Set(ahttp.HeaderContentType, ahttp.ContentTypeJSON.String())
req.Header.Set("X-Anti-CSRF-Token", secretstr)
req.Header.Set(ahttp.HeaderCookie, cookieValue)
req.Header.Set(ahttp.HeaderXRequestID, ess.NewGUID()+"jeeva")
result = fireRequest(t, req)
assert.Equal(t, 200, result.StatusCode)
assert.True(t, strings.Contains(result.Body, "JSON Payload recevied successfully"))
assert.True(t, strings.Contains(result.Body, "8253645635463"))
assert.True(t, strings.Contains(result.Body, "[email protected]"))
}
func TestAppMisc(t *testing.T) {
importPath := filepath.Join(testdataBaseDir(), "webapp1")
ts := newTestServer(t, importPath)
defer ts.Close()
t.Logf("Test Server URL [App Misc]: %s", ts.URL)
a := ts.app
assert.Equal(t, "web", a.Type())
assert.Equal(t, "aah framework web application", a.Desc())
assert.False(t, a.IsPackaged())
a.SetPackaged(true)
assert.True(t, a.IsPackaged())
assert.True(t, strings.Contains(strings.Join(a.EnvProfiles(), " "), "prod"))
_ = a.Run([]string{"-v"})
er := a.AddCommand(console.Command{Name: "test1"}, console.Command{Name: "test2"})
assert.Nil(t, er)
er = a.AddCommand(console.Command{Name: "vfs"})
assert.Equal(t, errors.New("aah: reserved command name 'vfs' cannot be used"), er)
er = a.AddCommand(console.Command{Name: "test2"})
assert.Equal(t, errors.New("aah: command name 'test2' already exists"), er)
// GH#244
testCmds := []console.Command{
console.Command{Name: "newcmd1"},
console.Command{
Name: "newcmd2",
Flags: []console.Flag{
console.StringFlag{
Name: "envprofile, e",
Value: "dev",
Usage: "Environment profile name to activate (e.g: dev, qa, prod)",
},
},
},
console.Command{
Name: "newcmd3sub",
Subcommands: []console.Command{
console.Command{Name: "newcmd3sub1"},
console.Command{
Name: "newcmd3sub2",
Flags: []console.Flag{
console.StringFlag{
Name: "envprofile, e",
Value: "dev",
Usage: "Environment profile name to activate (e.g: dev, qa, prod)",
},
},
},
},
},
}
er = a.AddCommand(testCmds...)
assert.Nil(t, er)
ll := a.NewChildLogger(log.Fields{"key1": "value1"})
assert.NotNil(t, ll)
// simualate CLI call
t.Log("simualate CLI call")
a.SetBuildInfo(nil)
a.settings.PackagedMode = false
err := a.InitForCLI(importPath)
assert.Nil(t, err)
// SSL
t.Log("SSL")
a.SetTLSConfig(nil)
a.Config().SetBool("server.ssl.enable", true)
a.Config().SetBool("server.ssl.lets_encrypt.enable", true)
err = a.settings.Refresh(a.Config())
assert.Nil(t, err)
// simulate import path
t.Log("simulate import path")
a.settings.ImportPath = "github.com/jeevatkm/noapp"
_ = a.initPath()
// assert.True(t, strings.HasPrefix(err.Error(), "import path does not exists:"))
// App packaged mode
t.Log("App packaged mode")
pa := newApp()
l, _ := log.New(config.NewEmpty())
pa.logger = l
pa.SetPackaged(true)
_ = pa.initPath()
// App embedded mode
assert.False(t, pa.VFS().IsEmbeddedMode())
pa.VFS().SetEmbeddedMode()
assert.True(t, pa.VFS().IsEmbeddedMode())
_ = pa.initPath()
// App WS engine
assert.Nil(t, pa.WSEngine())
// App Parse port
assert.Equal(t, "80", pa.parsePort(""))
}
func TestAppRecover(t *testing.T) {
importPath := filepath.Join(testdataBaseDir(), "webapp1")
a := newTestApp(t, importPath)
a.Log().(*log.Logger).SetWriter(ioutil.Discard)
panicTest(a)
}
func TestHotAppReload(t *testing.T) {
importPath := filepath.Join(testdataBaseDir(), "webapp1")
ts := newTestServer(t, importPath)
defer ts.Close()
t.Logf("Test Server URL [Hot Reload]: %s", ts.URL)
ts.app.performHotReload()
}
func TestLogInitRelativeFilePath(t *testing.T) {
logPath := filepath.Join(testdataBaseDir(), "sample-test-app.log")
defer ess.DeleteFiles(logPath)
// Relative path file
a := newApp()
cfg, _ := config.ParseString(`log {
receiver = "file"
file = "sample-test-app.log"
}`)
a.cfg = cfg
err := a.initLog()
assert.Nil(t, err)
_ = a.AddLoggerHook("myapphook", func(e log.Entry) {
t.Logf("%v", e)
})
}
func TestLogInitNoFilePath(t *testing.T) {
// No file input - auto location
logPath := filepath.Join(testdataBaseDir(), "wepapp1.log")
defer ess.DeleteFiles(logPath)
// Relative path file
a := newApp()
cfg, _ := config.ParseString(`log {
receiver = "file"
}`)
a.cfg = cfg
err := a.initLog()
assert.Nil(t, err)
_ = a.AddLoggerHook("myapphook", func(e log.Entry) {
t.Logf("%v", e)
})
}
func TestAccessLogInitAbsPath(t *testing.T) {
logPath := filepath.Join(testdataBaseDir(), "sample-test-access.log")
defer ess.DeleteFiles(logPath)
a := newApp()
cfg, _ := config.ParseString(fmt.Sprintf(`server {
access_log {
file = "%s"
}
}`, filepath.ToSlash(logPath)))
a.cfg = cfg
err := a.initAccessLog()
assert.Nil(t, err)
}
type testErrorController1 struct {
}
func (tec *testErrorController1) HandleError(err *Error) bool {
log.Info("I have handled it at controller level")
return true
}
func TestErrorCallControllerHandler(t *testing.T) {
req, err := http.NewRequest(ahttp.MethodGet, "http://localhost:8080", nil)
assert.Nil(t, err)
ctx := &Context{
Req: ahttp.AcquireRequest(req),
controller: &ainsp.Target{FqName: "testErrorController1"},
target: &testErrorController1{},
}
l, err := log.New(config.NewEmpty())
assert.Nil(t, err)
ctx.logger = l
ctx.Reply().ContentType("application/json")
ctx.Reply().BadRequest().Error(newError(nil, http.StatusBadRequest))
em := new(errorManager)
em.Handle(ctx)
}
func panicTest(a *Application) {
defer a.aahRecover()
panic("test panic")
}
func fireRequest(t *testing.T, req *http.Request) *testResult {
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Errorf("Request failed %s", err)
t.FailNow()
return nil
}
return &testResult{
StatusCode: resp.StatusCode,
Header: resp.Header,
Body: responseBody(resp),
Raw: resp,
}
}
//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// Test Server
//______________________________________________________________________________
func newTestServer(t *testing.T, importPath string) *testServer {
ts := &testServer{
app: newTestApp(t, importPath),
}
ts.server = httptest.NewServer(ts.app)
ts.URL = ts.server.URL
// Manually do it here here, for aah CLI test no issue `aah test` :)
ts.manualInit()
ts.DiscordLog()
return ts
}
func newTestApp(t *testing.T, importPath string) *Application {
a := newApp()
a.SetBuildInfo(&BuildInfo{
BinaryName: filepath.Base(importPath),
Timestamp: time.Now().Format(time.RFC3339),
Version: "1.0.0",
})
err := a.VFS().AddMount(a.VirtualBaseDir(), importPath)
assert.Nil(t, err, "not expecting any error")
a.settings.ImportPath = importPath
err = a.initPath()
assert.Nil(t, err, "app initPath failure")
err = a.initConfig()
assert.Nil(t, err, "app initConfig failure")
err = a.settings.Refresh(a.Config())
assert.Nil(t, err, "app settings failure")
err = a.initLog()
assert.Nil(t, err, "app log failure")
err = a.initApp()
assert.Nil(t, err, "app init failure")
return a
}
type testResult struct {
StatusCode int
Header http.Header
Body string
Raw *http.Response
}
// TestServer provides capabilities to test aah application end-to-end.
//
// Note: after sometime I will expose this test server, I'm not fully satisfied with
// the implementation yet! Because there are short comings in the test server....
type testServer struct {
URL string
app *Application
server *httptest.Server
}
func (ts *testServer) Close() {
ts.server.Close()
}
func (ts *testServer) DiscordLog() {
ts.app.Log().(*log.Logger).SetWriter(ioutil.Discard)
}
func (ts *testServer) UndiscordLog() {
ts.app.Log().(*log.Logger).SetWriter(os.Stdout)
}
// It a workaround to init required things for application, since test `webapp1`
// residing in `aahframework.org/aah.v0/testdata/webapp1`.
//
// This is not required for actual application residing in $GOPATH :)
func (ts *testServer) manualInit() {
// adding middlewares
ts.app.he.Middlewares(
RouteMiddleware,
CORSMiddleware,
BindMiddleware,
AntiCSRFMiddleware,
AuthcAuthzMiddleware,
ActionMiddleware,
)
// adding controller
ts.app.AddController((*testSiteController)(nil), []*ainsp.Method{
{Name: "Index"},
{Name: "Text"},
{
Name: "Redirect",
Parameters: []*ainsp.Parameter{
{Name: "mode", Type: reflect.TypeOf((*string)(nil))},
},
},
{
Name: "FormSubmit",
Parameters: []*ainsp.Parameter{
{Name: "id", Type: reflect.TypeOf((*int)(nil))},
{Name: "info", Type: reflect.TypeOf((**sample)(nil))},
},
},
{
Name: "CreateRecord",
Parameters: []*ainsp.Parameter{
{Name: "info", Type: reflect.TypeOf((**sampleJSON)(nil))},
},
},
{Name: "XML"},
{
Name: "JSONP",
Parameters: []*ainsp.Parameter{
{Name: "callback", Type: reflect.TypeOf((*string)(nil))},
},
},
{Name: "SecureJSON"},
{Name: "TriggerPanic"},
{Name: "BinaryBytes"},
{Name: "SendFile"},
{Name: "Cookies"},
})
// reset controller namespace and key
cregistry := &ainsp.TargetRegistry{Registry: make(map[string]*ainsp.Target), SearchType: ctxPtrType}
for k, v := range ts.app.he.registry.Registry {
v.Namespace = ""
cregistry.Registry[path.Base(k)] = v
}
ts.app.he.registry = cregistry
}
// Test types
type sample struct {
ProductID int `bind:"id"`
ProductName string `bind:"product_name"`
Username string `bind:"username"`
Email string `bind:"email"`
Page int `bind:"page"`
Count string `bind:"count"`
}
type sampleJSON struct {
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Email string `json:"email"`
Number int `json:"number"`
}
// Test Controller
type testSiteController struct {
*Context
}
func (s *testSiteController) Index() {
s.Reply().HTML(Data{
"Message": "Welcome to aah framework - Test Application webapp1",
"IsSubDomain": s.Subdomain(),
"StaticRoute": s.IsStaticRoute(),
})
}
func (s *testSiteController) Text() {
s.Reply().Text(s.Msg("test.text.msg.render"))
}
func (s *testSiteController) Redirect(mode string) {
switch mode {
case "status":
s.Reply().RedirectWithStatus(s.RouteURL("text_get"), 307)
case "text_get":
s.Reply().Redirect(s.RouteURLNamedArgs("text_get", map[string]interface{}{
"param1": "param1value",
"Param2": "Param2Value",
}))
default:
s.Reply().Redirect(s.RouteURL("index"))
}
}
func (s *testSiteController) FormSubmit(id int, info *sample) {
s.Session().Set("session_val1", "This is my session 1 value")
s.Reply().JSON(Data{
"message": "Data recevied successfully",
"success": true,
"id": id,
"data": info,
})
}
func (s *testSiteController) CreateRecord(info *sampleJSON) {
s.Reply().JSON(Data{
"message": "JSON Payload recevied successfully",
"success": true,
"data": info,
})
}
func (s *testSiteController) XML() {
s.Reply().XML(Data{
"message": "This is XML payload result",
"success": true,
})
}
func (s *testSiteController) JSONP(callback string) {
s.Reply().JSONP(sample{
Username: "myuser_name",
ProductName: "JSONP product",
ProductID: 190398398,
Email: "[email protected]",
Page: 2,
Count: "1000",
}, callback)
}
func (s *testSiteController) SecureJSON() {
s.Reply().JSONSecure(sample{
Username: "myuser_name",
ProductName: "JSONP product",
ProductID: 190398398,
Email: "[email protected]",
Page: 2,
Count: "1000",
})
}
func (s *testSiteController) TriggerPanic() {
if s.Req.AcceptContentType().IsEqual("application/json") {
s.Reply().ContentType(ahttp.ContentTypeJSON.String())
}
panic("This panic flow test and recovery")
}
func (s *testSiteController) BinaryBytes() {
s.Reply().
HeaderAppend(ahttp.HeaderContentType, ahttp.ContentTypePlainText.String()).
Binary([]byte("This is my Binary Bytes"))
}
func (s *testSiteController) SendFile() {
s.Reply().
Header("X-Before-Interceptor", "").
Header(ahttp.HeaderContentType, ""). // this is just invoke the method
Header(ahttp.HeaderContentType, "text/css").
FileInline(filepath.Join("static", "css", "aah.css"), "aah.css")
s.Reply().IsContentTypeSet()
}
func (s *testSiteController) Cookies() {
s.Reply().Cookie(&http.Cookie{
Name: "test_cookie_1",
Value: "This is test cookie value 1",
Path: "/",
Expires: time.Now().AddDate(1, 0, 0),
HttpOnly: true,
}).
Cookie(&http.Cookie{
Name: "test_cookie_2",
Value: "This is test cookie value 2",
Path: "/",
Expires: time.Now().AddDate(1, 0, 0),
HttpOnly: true,
}).Text("Hey I'm sending cookies for you :)")
}
func (s *testSiteController) HandleError(err *Error) bool {
s.Log().Infof("we got the callbakc from error handler: %s", err)
s.Reply().Header("X-Cntrl-ErrorHandler", "true")
return false
}
func (s *testSiteController) Before() {
s.Reply().Header("X-Before-Interceptor", "Before Called successfully")
s.Log().Info("Before controller interceptor")
}
func (s *testSiteController) After() {
s.Reply().Header("X-After-Interceptor", "After Called successfully")
s.Log().Info("After controller interceptor")
}
func (s *testSiteController) Finally() {
s.Reply().Header("X-Finally-Interceptor", "Finally Called successfully")
s.Log().Info("Finally controller interceptor")
}
func (s *testSiteController) BeforeText() {
s.Reply().Header("X-BeforeText-Interceptor", "BeforeText Called successfully")
s.Log().Info("Before action Text interceptor")
}
func (s *testSiteController) AfterText() {
s.Reply().Header("X-AfterText-Interceptor", "AfterText Called successfully")
s.Log().Info("After action Text interceptor")
}
func (s *testSiteController) FinallyText() {
s.Reply().Header("X-FinallyText-Interceptor", "FinallyText Called successfully")
s.Log().Info("Finally action Text interceptor")
}
//‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
// Test util methods
//______________________________________________________________________________
func testdataBaseDir() string {
wd, _ := os.Getwd()
if idx := strings.Index(wd, "testdata"); idx > 0 {
wd = wd[:idx]
}
return filepath.Join(wd, "testdata")
}
func responseBody(res *http.Response) string {
body := res.Body
defer ess.CloseQuietly(body)
if strings.Contains(res.Header.Get(ahttp.HeaderContentEncoding), "gzip") {
body, _ = gzip.NewReader(body)
}
buf := new(bytes.Buffer)
io.Copy(buf, body)
return buf.String()
}