Source

go-fastweb / fastweb.go

Full commit
  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
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
// vim: set syntax=go autoindent:
// Copyright 2010 Ivan Wong. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package fastweb

import (
	"bytes"
	"fmt"
	"io"
	"log"
	"math/rand"
	"net"
	"net/url"
	"net/http"
	"path/filepath"
	//"net/http/fcgi"
	"os"
	"reflect"
	"regexp"
	"strconv"
	"strings"
	"time"
	"text/template"
)

const (
	IntParam = 1
	StrParam = 2
)

type ControllerInterface interface {
	Init()
	DefaultAction() string
	SetEnv(env *env)
	PreFilter()
	Render()
	SetContext(ctxt ControllerInterface)
	StartSession()
	CloseSession()
}

type Error interface {
	error
	Type() string
}

type ErrorStruct struct {
	typ     string
	message string
}

type methodInfo struct {
	name       string
	method     reflect.Value
	nparams    int
	paramTypes []int
}

type controllerInfo struct {
	name              string
	controller        ControllerInterface
	controllerType    reflect.Type
	controllerPtrType reflect.Type
	methodMap         map[string]*methodInfo
}

type Application struct {
	controllerMap     map[string]*controllerInfo
	defaultController string
	fileServer        http.Handler
}

type env struct {
	path        string
	controller  string
	lcontroller string
	action      string
	laction     string
	params      []string
	request     *http.Request
	response    http.ResponseWriter
	body        string
}

type cookie struct {
	value    string
	expire   time.Time
	path     string
	domain   string
	secure   bool
	httpOnly bool
}

type Controller struct {
	Path        string
	Name        string
	LName       string
	Action      string
	LAction     string
	PageTitle   string
	Layout      string
	ContentType string
	Body        string
	Session     *Session
	ctxt        ControllerInterface
	Request     *http.Request
	Response    http.ResponseWriter
	preRenered  bool
}

func NewError(typ string, message string) *ErrorStruct {
	return &ErrorStruct{typ, message}
}

func (e *ErrorStruct) Error() string { return e.message }

func (e *ErrorStruct) Type() string { return e.typ }

func (c *Controller) Init() {
	c.PageTitle = ""
	c.Layout = "default"
	c.ContentType = "text/html; charset=utf-8"
}

func (c *Controller) DefaultAction() string { return "Index" }

func (c *Controller) SetEnv(env *env) {
	c.Name = env.controller
	c.LName = env.lcontroller
	c.Action = env.action
	c.LAction = env.laction
	c.Path = env.path
	c.Request = env.request
	c.Response = env.response
	c.Body = env.body
}

func (c *Controller) PreFilter() {}

type tmplInfo struct {
	tmpl  *template.Template
	mtime time.Time
}

var tmplCache map[string]*tmplInfo = make(map[string]*tmplInfo)

func loadTemplate(fname string) (*template.Template, error) {
	dir, e := os.Stat(fname)
	if e != nil {
		return nil, e
	}
	if !!dir.IsDir() {
		return nil, NewError("Generic", "'"+fname+"' is not a regular file")
	}
	ti, _ := tmplCache[fname]
	if ti == nil || dir.ModTime().After(ti.mtime) {
		t, e := template.ParseFiles(fname)
		if e != nil {
			return nil, e
		}
		ti = &tmplInfo{
			mtime: dir.ModTime(),
			tmpl:  t,
		}
		tmplCache[fname] = ti
	}
	return ti.tmpl, nil
}

func (c *Controller) SetContext(ctxt ControllerInterface) {
	if c.ctxt == nil {
		c.ctxt = ctxt
	}
}

func executeTemplate(fname string, t *template.Template, w io.Writer, data interface{}) {
	e := t.Execute(w, data)
	if e != nil {
		log.Printf("error occurred during executing template %s: %s", fname, e)
	}
}

func (c *Controller) RenderContent() error {
	fname := "views/" + c.LName + "/" + c.LAction + ".tpl"
	t, e := loadTemplate(fname)
	if e != nil {
		log.Print(e)
		c.Response.Write([]byte("Server error processing request"))
		// Dump c.ctxt contents
	} else {
		executeTemplate(fname, t, c.Response, c.ctxt)
	}
	return nil
}

func (c *Controller) renderTemplate(fname string) {
	t, e := loadTemplate(fname)
	if e == nil {
		executeTemplate(fname, t, c.Response, c.ctxt)
	} else {
		log.Printf("failed to load template %s: %s", fname, e)
	}
}

func (c *Controller) RenderElement(name string) string {
	c.renderTemplate("views/elements/" + name + ".tpl")
	return ""
}

func (c *Controller) RenderControllerElement(name string) string {
	c.renderTemplate("views/" + c.LName + "/elements/" + name + ".tpl")
	return ""
}

func (c *Controller) Render() {
	if len(c.Layout) == 0 {
		c.RenderContent()
		return
	}

	fname := "views/layouts/" + c.Layout + ".tpl"
	t, e := loadTemplate(fname)
	if e != nil {
		log.Printf("failed to load layout template %s: %s", fname, e)
		c.RenderContent()
	} else {
		executeTemplate(fname, t, c.Response, c.ctxt)
	}
}

func (c *Controller) SetCookie(key string, value string) {
	http.SetCookie(c.Response, &http.Cookie{
		Name: key,
		Value: value,
		Path: "",
		Domain: "",
		Expires: time.Time{},
		Secure: false,
		HttpOnly: false,
	})
}

func (c *Controller) SetCookieFull(key string, value string, expire time.Time, path string, domain string, secure bool, httpOnly bool) {
	http.SetCookie(c.Response, &http.Cookie{
		Name: key,
		Value: value,
		Path: path,
		Domain: domain,
		Expires: expire,
		Secure: secure,
		HttpOnly: httpOnly,
	})
}

func (c *Controller) StartSession() {
	if c.Session != nil {
		return
	}

	c.Session = GetSession(c)
}

func (c *Controller) CloseSession() {
	if c.Session == nil {
		return
	}

	c.Session.Close()
}

type ErrorHandler struct {
	Controller
	typ string
}

func NewErrorHandler(e Error, response http.ResponseWriter, r *http.Request) *ErrorHandler {
	eh := &ErrorHandler{
		typ: e.Type(),
	}
	eh.Request = r
	eh.Response = response
	eh.Init()
	eh.SetContext(eh)
	return eh
}

func (eh *ErrorHandler) RenderContent() {
	fname := "views/errors/" + eh.typ + ".tpl"
	t, e := loadTemplate(fname)
	if e != nil {
		var msg string
		switch eh.typ {
		case "PageNotFound":
			msg = "Hmm, the page you’re looking for can't be found."
		default:
			msg = "We're sorry, but there was an error processing your request. Please try again later."
		}
		fmt.Fprintf(eh.Response, "%s", msg)
	} else {
		executeTemplate(fname, t, eh.Response, eh)
	}
}

func titleCase(s string) string {
	if len(s) > 0 {
		parts := strings.Split(s, "_")
		for i, p := range parts {
			l := len(p)
			if l > 0 {
				parts[i] = strings.ToUpper(string(p[0])) + p[1:len(p)]
			} else {
				parts[i] = ""
			}
		}
		return strings.Join(parts, "")
	}
	return s
}

func deTitleCase(s string) string {
	if len(s) > 0 {
		var o string
		for i, c := range s {
			if c >= 'A' && c <= 'Z' {
				if i > 0 {
					o += "_"
				}
				o += strings.ToLower(string(c))
			} else {
				o += string(c)
			}
		}
		return o
	}
	return s
}

func parseKeyValueString(m map[string][]string, s string) error {
	if s == "" {
		return nil
	}

	// copied from pkg/http/request.go
	for _, kv := range strings.Split(s, "&") {
		if kv == "" {
			continue
		}
		kvPair := strings.SplitN(kv, "=", 2)

		var key, value string
		var e error
		key, e = url.QueryUnescape(kvPair[0])
		if e == nil && len(kvPair) > 1 {
			value, e = url.QueryUnescape(kvPair[1])
		}
		if e != nil {
			return e
		}

		vec, ok := m[key]
		if !ok {
			vec = make([]string, 1)
		}
		m[key] = append(vec, value)
	}

	return nil
}

var boundaryRE, _ = regexp.Compile("boundary=\"?([^\";,]+)\"?")

type multipartReader struct {
	rd   io.Reader
	bd   []byte
	buf  []byte
	head int
	tail int
	eof  bool
	done bool
}

func newMultipartReader(rd io.Reader, bd string) *multipartReader {
	return &multipartReader{
		rd:   rd,
		bd:   []byte("\r\n--" + bd),
		buf:  make([]byte, 4096),
		head: 0,
		tail: 0,
	}
}

func (md *multipartReader) finished() bool { return md.done }

func (md *multipartReader) read(delim []byte) ([]byte, error) {
	if md.done {
		return nil, io.EOF
	}

	if !md.eof && md.tail < len(md.buf) {
		n, e := md.rd.Read(md.buf[md.tail:len(md.buf)])
		if e != nil {
			if e != io.EOF {
				return nil, e
			}
			md.eof = true
		}
		md.tail += n
	}

	if i := bytes.Index(md.buf[md.head:md.tail], delim); i >= 0 {
		s := make([]byte, i)
		copy(s, md.buf[md.head:md.head+i])
		md.head += i + len(delim)
		return s, io.EOF
	}

	if md.eof {
		md.done = true
		return md.buf[md.head:md.tail], io.EOF
	}

	bf := md.tail - md.head
	keep := len(delim) - 1
	if keep > bf {
		keep = bf
	}
	stop := md.tail - keep
	n := stop - md.head
	s := make([]byte, n)
	if n > 0 {
		copy(s, md.buf[md.head:stop])
	}

	copy(md.buf[0:keep], md.buf[stop:md.tail])
	md.head = 0
	md.tail = keep

	return s, nil
}

func (md *multipartReader) readFirstLine() { md.readStringUntil(md.bd[2:len(md.bd)], false) }

var crlf2 = []byte{'\r', '\n', '\r', '\n'}

type byteConsumer func([]byte) error

func (md *multipartReader) readUntil(delim []byte, checkEnd bool, f byteConsumer) error {
	for {
		b, e := md.read(delim)
		if b != nil {
			if e := f(b); e != nil {
				return e
			}
		}
		if e != nil {
			if e == io.EOF {
				if checkEnd && md.tail-md.head >= 2 && string(md.buf[md.head:md.head+2]) == "--" {
					md.done = true
				}
				break
			}
			return e
		}
	}

	return nil
}

func (md *multipartReader) readStringUntil(delim []byte, checkEnd bool) (string, error) {
	var s string
	e := md.readUntil(delim, checkEnd, func(b []byte) error {
		s += string(b)
		return nil
	})
	return s, e
}

type hdrInfo struct {
	key     string
	val     string
	attribs map[string]string
}

func parseHeader(line string) *hdrInfo {
	var key, attrib string
	var hdr *hdrInfo
	var attribs map[string]string
	var j int
	phase := 0
	line += ";"
	for i, c := range line {
		switch phase {
		case 0:
			if c == ':' {
				key = strings.TrimSpace(line[0:i])
				phase++
				j = i + 1
			}
		case 1:
			if c == ';' {
				attribs = make(map[string]string)
				hdr = &hdrInfo{
					key:     key,
					val:     strings.TrimSpace(line[j:i]),
					attribs: attribs,
				}
				phase++
				j = i + 1
			}
		case 2:
			if c == '=' {
				attrib = strings.TrimSpace(line[j:i])
				phase++
				j = i + 1
			}
		case 3:
			if c == '"' {
				phase++
				j = i + 1
			} else if c == ';' {
				attribs[attrib] = strings.TrimSpace(line[j:i])
				phase = 2
				j = i + 1
			}
		case 4:
			if c == '\\' {
				phase++
			} else if c == '"' {
				attribs[attrib] = line[j:i]
				phase += 2
			}
		case 5:
			phase--
		case 6:
			if c == ';' {
				phase = 2
				j = i + 1
			}
		}
	}
	return hdr
}

func (md *multipartReader) readHeaders() (map[string]*hdrInfo, error) {
	s, _ := md.readStringUntil(crlf2, false)
	lines := strings.Split(s[2:len(s)], "\r\n")
	hdrs := make(map[string]*hdrInfo)
	for _, line := range lines {
		if hdr := parseHeader(line); hdr != nil {
			hdrs[hdr.key] = hdr
		}
	}
	return hdrs, nil
}

func (md *multipartReader) readBody() (string, error) {
	return md.readStringUntil(md.bd, true)
}

var pads = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"

func tempfile() (*os.File, error) {
	tmpdir := os.Getenv("TMPDIR")
	if tmpdir == "" {
		tmpdir = "/tmp"
	}

	for {
		var s string
		for i := 0; i < 10; i++ {
			s += string(pads[rand.Int()%len(pads)])
		}
		file, e := os.OpenFile(tmpdir+"/fastweb."+s, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)
		if e == nil {
			return file, e
		}
		pe, ok := e.(*os.PathError)
		if !ok || !os.IsExist(pe.Err) {
			return nil, e
		}
	}

	return nil, nil
}

func (a *Application) getEnv(response http.ResponseWriter, r *http.Request) *env {
	var params []string
	var lname string
	var laction string

	path := r.URL.Path

	pparts := strings.Split(path, "/")
	n := len(pparts)
	if n > 1 {
		lname = pparts[1]
		if n > 2 {
			laction = pparts[2]
			if n > 3 {
				if pparts[n-1] == "" {
					n--
				}
				params = pparts[3:n]
			}
		}
	}

	name := titleCase(lname)
	action := titleCase(laction)

	var body string
	e := r.ParseMultipartForm(16000000)
	if e != nil {
		log.Printf("failed to parse form: %s", e.Error())
	} else {
		bodyReader := r.Body
		data := make([]byte, 2048)
		bodyReader.Read(data)
		body = string(data)
	}

	return &env{
		path:        path,
		controller:  name,
		lcontroller: lname,
		action:      action,
		laction:     laction,
		params:      params,
		request:     r,
		response:    response,
		body:        body,
	}
}

func (a *Application) route(response http.ResponseWriter, r *http.Request) error {
	env := a.getEnv(response, r)

	if env.controller == "" {
		env.controller = a.defaultController
		env.lcontroller = deTitleCase(env.controller)
	}

	cinfo, _ := a.controllerMap[env.controller]
	if cinfo == nil {
		return NewError("PageNotFound", "controller class '"+env.controller+"' not found")
	}

	vc := reflect.New(cinfo.controllerType)
	vi := reflect.New(cinfo.controllerPtrType).Elem()
	vi.Set(vc.Elem().Addr())
	c := vi.Interface().(ControllerInterface)

	if env.action == "" {
		env.action = c.DefaultAction()
		env.laction = deTitleCase(env.action)
	}

	minfo, _ := cinfo.methodMap[env.action]
	if minfo == nil {
		return NewError("PageNotFound", "action '"+env.action+"' is not implemented in controller '"+env.controller+"'")
	}

	if minfo.nparams > len(env.params) {
		return NewError("PageNotFound", "not enough parameter")
	}

	pv := make([]reflect.Value, minfo.nparams+1)
	pv[0] = vc

	for i := 0; i < minfo.nparams; i++ {
		p := env.params[i]
		switch minfo.paramTypes[i] {
		case StrParam:
			pv[i+1] = reflect.ValueOf(p)
		case IntParam:
			x, e2 := strconv.Atoi(p)
			if e2 != nil {
				return NewError("PageNotFound", fmt.Sprintf("parameter %d must be an integer, input: %s", i+1, p))
			}
			pv[i+1] = reflect.ValueOf(x)
		}
	}

	c.Init()
	c.SetEnv(env)
	c.PreFilter()

	eval := minfo.method.Call(pv)[0]
	if !eval.IsNil() {
		elemval := eval.Elem()
		return elemval.Interface().(error)
	}

	c.SetContext(c)
	c.Render()
	c.CloseSession()

	return nil
}

func (a *Application) ServeHTTP(response http.ResponseWriter, request *http.Request) {
	e := a.route(response, request)

	if e != nil {
		log.Printf("error = %v", e)
		p := "htdocs/"+request.URL.Path
		path := strings.Split(p, "/")
		_, e := os.Stat(filepath.Join(path...))
		if e != nil {
			ee := NewError("Generic", e.Error())
			log.Printf("%s", e.Error())
			eh := NewErrorHandler(ee, response, request)
			eh.Render()
		} else {
			a.fileServer.ServeHTTP(response, request)
		}
	}
}

func NewApplication() *Application {
	return &Application{
		controllerMap:     make(map[string]*controllerInfo),
		defaultController: "Default",
		fileServer: http.FileServer(http.Dir("htdocs")),
	}
}

func (a *Application) RegisterController(c ControllerInterface) {
	v := reflect.ValueOf(c)
	pt := v.Type()
	t := v.Elem().Type()
	name := t.Name()

	mmap := make(map[string]*methodInfo)

	n := pt.NumMethod()
	for i := 0; i < n; i++ {
		m := pt.Method(i)
		name := m.Name
		switch name {
		case "SetEnv", "Render", "DefaultAction", "Init", "PreFilter", "SetContext":
			continue
		}
		mt := m.Type
		if mt.NumOut() != 1 {
			continue
		}
		mo := mt.Out(0)
		switch mo.Kind() {
		case reflect.Interface:
			if mo.Name() != "error" {
				continue
			}
		default:
			continue
		}
		nin := mt.NumIn() - 1
		ptypes := make([]int, nin)
		for j := 0; j < nin; j++ {
			in := mt.In(j + 1)
			switch in.Kind() {
			case reflect.Int:
				ptypes[j] = IntParam
			case reflect.String:
				ptypes[j] = StrParam
			default:
				continue
			}
		}
		mmap[name] = &methodInfo{
			name:       name,
			method:     m.Func,
			nparams:    nin,
			paramTypes: ptypes,
		}
	}

	a.controllerMap[name] = &controllerInfo{
		name:              name,
		controller:        c,
		controllerType:    t,
		controllerPtrType: pt,
		methodMap:         mmap,
	}
}

func (a *Application) Run(addr string) error {
	rand.Seed(time.Now().UnixNano())
	listener, err := net.Listen("tcp", addr)
	if err != nil { panic(err) }
	return http.Serve(listener, a)
}