diff options
author | Gogs <gogitservice@gmail.com> | 2014-03-19 21:57:55 +0800 |
---|---|---|
committer | Gogs <gogitservice@gmail.com> | 2014-03-19 21:58:51 +0800 |
commit | 56af7e99a819758c6bedc6d745a9f810f3fc050d (patch) | |
tree | 29de4db653e1d59e271917812e9dc669acb7f209 /modules | |
parent | 0da4975f4ffca8dd85213c19600730ee52349e2a (diff) | |
download | gitea-56af7e99a819758c6bedc6d745a9f810f3fc050d.tar.gz gitea-56af7e99a819758c6bedc6d745a9f810f3fc050d.zip |
fork render
Diffstat (limited to 'modules')
-rw-r--r-- | modules/base/template.go | 5 | ||||
-rw-r--r-- | modules/middleware/auth.go | 4 | ||||
-rw-r--r-- | modules/middleware/context.go | 28 | ||||
-rw-r--r-- | modules/middleware/render.go | 286 | ||||
-rw-r--r-- | modules/middleware/repo.go | 6 |
5 files changed, 308 insertions, 21 deletions
diff --git a/modules/base/template.go b/modules/base/template.go index db79340e75..23d3d27713 100644 --- a/modules/base/template.go +++ b/modules/base/template.go @@ -6,7 +6,9 @@ package base import ( "container/list" + "fmt" "html/template" + "time" ) func Str2html(raw string) template.HTML { @@ -40,6 +42,9 @@ var TemplateFuncs template.FuncMap = map[string]interface{}{ "AppDomain": func() string { return Domain }, + "LoadTimes": func(startTime time.Time) string { + return fmt.Sprint(time.Since(startTime).Nanoseconds()/1e6) + "ms" + }, "AvatarLink": AvatarLink, "str2html": Str2html, "TimeSince": TimeSince, diff --git a/modules/middleware/auth.go b/modules/middleware/auth.go index 84bbc7f45f..ed847dd83c 100644 --- a/modules/middleware/auth.go +++ b/modules/middleware/auth.go @@ -13,7 +13,7 @@ func SignInRequire(redirect bool) martini.Handler { return func(ctx *Context) { if !ctx.IsSigned { if redirect { - ctx.Render.Redirect("/") + ctx.Redirect("/") } return } else if !ctx.User.IsActive { @@ -28,7 +28,7 @@ func SignInRequire(redirect bool) martini.Handler { func SignOutRequire() martini.Handler { return func(ctx *Context) { if ctx.IsSigned { - ctx.Render.Redirect("/") + ctx.Redirect("/") } } } diff --git a/modules/middleware/context.go b/modules/middleware/context.go index 7eaf665005..c97c3299c4 100644 --- a/modules/middleware/context.go +++ b/modules/middleware/context.go @@ -7,26 +7,24 @@ package middleware import ( "fmt" "net/http" + "time" "github.com/codegangsta/martini" - "github.com/martini-contrib/render" "github.com/martini-contrib/sessions" "github.com/gogits/gogs/models" "github.com/gogits/gogs/modules/auth" - "github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/log" ) // Context represents context of a request. type Context struct { + *Render c martini.Context p martini.Params Req *http.Request Res http.ResponseWriter Session sessions.Session - Data base.TmplData - Render render.Render User *models.User IsSigned bool @@ -62,27 +60,25 @@ func (ctx *Context) RenderWithErr(msg, tpl string, form auth.Form) { ctx.Data["HasError"] = true ctx.Data["ErrorMsg"] = msg auth.AssignForm(form, ctx.Data) - ctx.Render.HTML(200, tpl, ctx.Data) + ctx.HTML(200, tpl, ctx.Data) } // Handle handles and logs error by given status. func (ctx *Context) Handle(status int, title string, err error) { log.Error("%s: %v", title, err) if martini.Dev == martini.Prod { - ctx.Render.HTML(500, "status/500", ctx.Data) + ctx.HTML(500, "status/500", ctx.Data) return } ctx.Data["ErrorMsg"] = err - ctx.Render.HTML(status, fmt.Sprintf("status/%d", status), ctx.Data) + ctx.HTML(status, fmt.Sprintf("status/%d", status), ctx.Data) } // InitContext initializes a classic context for a request. func InitContext() martini.Handler { return func(res http.ResponseWriter, r *http.Request, c martini.Context, - session sessions.Session, rd render.Render) { - - data := base.TmplData{} + session sessions.Session, rd *Render) { ctx := &Context{ c: c, @@ -90,7 +86,6 @@ func InitContext() martini.Handler { Req: r, Res: res, Session: session, - Data: data, Render: rd, } @@ -99,16 +94,17 @@ func InitContext() martini.Handler { ctx.User = user ctx.IsSigned = user != nil - data["IsSigned"] = ctx.IsSigned + ctx.Data["IsSigned"] = ctx.IsSigned if user != nil { - data["SignedUser"] = user - data["SignedUserId"] = user.Id - data["SignedUserName"] = user.LowerName + ctx.Data["SignedUser"] = user + ctx.Data["SignedUserId"] = user.Id + ctx.Data["SignedUserName"] = user.LowerName } + ctx.Data["PageStartTime"] = time.Now() + c.Map(ctx) - c.Map(data) c.Next() } diff --git a/modules/middleware/render.go b/modules/middleware/render.go new file mode 100644 index 0000000000..8a54183135 --- /dev/null +++ b/modules/middleware/render.go @@ -0,0 +1,286 @@ +// Copyright 2014 The Gogs Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +// foked from https://github.com/martini-contrib/render/blob/master/render.go +package middleware + +import ( + "bytes" + "encoding/json" + "fmt" + "html/template" + "io" + "io/ioutil" + "net/http" + "os" + "path/filepath" + "time" + + "github.com/codegangsta/martini" + + "github.com/gogits/gogs/modules/base" +) + +const ( + ContentType = "Content-Type" + ContentLength = "Content-Length" + ContentJSON = "application/json" + ContentHTML = "text/html" + ContentXHTML = "application/xhtml+xml" + defaultCharset = "UTF-8" +) + +var helperFuncs = template.FuncMap{ + "yield": func() (string, error) { + return "", fmt.Errorf("yield called with no layout defined") + }, +} + +type Delims struct { + Left string + + Right string +} + +type RenderOptions struct { + Directory string + + Layout string + + Extensions []string + + Funcs []template.FuncMap + + Delims Delims + + Charset string + + IndentJSON bool + + HTMLContentType string +} + +type HTMLOptions struct { + Layout string +} + +func Renderer(options ...RenderOptions) martini.Handler { + opt := prepareOptions(options) + cs := prepareCharset(opt.Charset) + t := compile(opt) + return func(res http.ResponseWriter, req *http.Request, c martini.Context) { + var tc *template.Template + if martini.Env == martini.Dev { + + tc = compile(opt) + } else { + + tc, _ = t.Clone() + } + + rd := &Render{res, req, tc, opt, cs, base.TmplData{}, time.Time{}} + + rd.Data["TmplLoadTimes"] = func() string { + if rd.startTime.IsZero() { + return "" + } + return fmt.Sprint(time.Since(rd.startTime).Nanoseconds()/1e6) + "ms" + } + + c.Map(rd.Data) + c.Map(rd) + } +} + +func prepareCharset(charset string) string { + if len(charset) != 0 { + return "; charset=" + charset + } + + return "; charset=" + defaultCharset +} + +func prepareOptions(options []RenderOptions) RenderOptions { + var opt RenderOptions + if len(options) > 0 { + opt = options[0] + } + + if len(opt.Directory) == 0 { + opt.Directory = "templates" + } + if len(opt.Extensions) == 0 { + opt.Extensions = []string{".tmpl"} + } + if len(opt.HTMLContentType) == 0 { + opt.HTMLContentType = ContentHTML + } + + return opt +} + +func compile(options RenderOptions) *template.Template { + dir := options.Directory + t := template.New(dir) + t.Delims(options.Delims.Left, options.Delims.Right) + + template.Must(t.Parse("Martini")) + + filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { + r, err := filepath.Rel(dir, path) + if err != nil { + return err + } + + ext := filepath.Ext(r) + for _, extension := range options.Extensions { + if ext == extension { + + buf, err := ioutil.ReadFile(path) + if err != nil { + panic(err) + } + + name := (r[0 : len(r)-len(ext)]) + tmpl := t.New(filepath.ToSlash(name)) + + for _, funcs := range options.Funcs { + tmpl.Funcs(funcs) + } + + template.Must(tmpl.Funcs(helperFuncs).Parse(string(buf))) + break + } + } + + return nil + }) + + return t +} + +type Render struct { + http.ResponseWriter + req *http.Request + t *template.Template + opt RenderOptions + compiledCharset string + + Data base.TmplData + + startTime time.Time +} + +func (r *Render) JSON(status int, v interface{}) { + var result []byte + var err error + if r.opt.IndentJSON { + result, err = json.MarshalIndent(v, "", " ") + } else { + result, err = json.Marshal(v) + } + if err != nil { + http.Error(r, err.Error(), 500) + return + } + + r.Header().Set(ContentType, ContentJSON+r.compiledCharset) + r.WriteHeader(status) + r.Write(result) +} + +func (r *Render) JSONString(v interface{}) (string, error) { + var result []byte + var err error + if r.opt.IndentJSON { + result, err = json.MarshalIndent(v, "", " ") + } else { + result, err = json.Marshal(v) + } + if err != nil { + return "", err + } + return string(result), nil +} + +func (r *Render) renderBytes(name string, binding interface{}, htmlOpt ...HTMLOptions) (*bytes.Buffer, error) { + opt := r.prepareHTMLOptions(htmlOpt) + + if len(opt.Layout) > 0 { + r.addYield(name, binding) + name = opt.Layout + } + + out, err := r.execute(name, binding) + if err != nil { + return nil, err + } + + return out, nil +} + +func (r *Render) HTML(status int, name string, binding interface{}, htmlOpt ...HTMLOptions) { + r.startTime = time.Now() + + out, err := r.renderBytes(name, binding, htmlOpt...) + if err != nil { + http.Error(r, err.Error(), http.StatusInternalServerError) + return + } + + r.Header().Set(ContentType, r.opt.HTMLContentType+r.compiledCharset) + r.WriteHeader(status) + io.Copy(r, out) +} + +func (r *Render) HTMLString(name string, binding interface{}, htmlOpt ...HTMLOptions) (string, error) { + if out, err := r.renderBytes(name, binding, htmlOpt...); err != nil { + return "", err + } else { + return out.String(), nil + } +} + +func (r *Render) Error(status int) { + r.WriteHeader(status) +} + +func (r *Render) Redirect(location string, status ...int) { + code := http.StatusFound + if len(status) == 1 { + code = status[0] + } + + http.Redirect(r, r.req, location, code) +} + +func (r *Render) Template() *template.Template { + return r.t +} + +func (r *Render) execute(name string, binding interface{}) (*bytes.Buffer, error) { + buf := new(bytes.Buffer) + return buf, r.t.ExecuteTemplate(buf, name, binding) +} + +func (r *Render) addYield(name string, binding interface{}) { + funcs := template.FuncMap{ + "yield": func() (template.HTML, error) { + buf, err := r.execute(name, binding) + + return template.HTML(buf.String()), err + }, + } + r.t.Funcs(funcs) +} + +func (r *Render) prepareHTMLOptions(htmlOpt []HTMLOptions) HTMLOptions { + if len(htmlOpt) > 0 { + return htmlOpt[0] + } + + return HTMLOptions{ + Layout: r.opt.Layout, + } +} diff --git a/modules/middleware/repo.go b/modules/middleware/repo.go index db29bd116e..a12212affa 100644 --- a/modules/middleware/repo.go +++ b/modules/middleware/repo.go @@ -30,7 +30,7 @@ func RepoAssignment(redirect bool) martini.Handler { user, err = models.GetUserByName(params["username"]) if err != nil { if redirect { - ctx.Render.Redirect("/") + ctx.Redirect("/") return } ctx.Handle(200, "RepoAssignment", err) @@ -42,7 +42,7 @@ func RepoAssignment(redirect bool) martini.Handler { if user == nil { if redirect { - ctx.Render.Redirect("/") + ctx.Redirect("/") return } ctx.Handle(200, "RepoAssignment", errors.New("invliad user account for single repository")) @@ -55,7 +55,7 @@ func RepoAssignment(redirect bool) martini.Handler { repo, err := models.GetRepositoryByName(user, params["reponame"]) if err != nil { if redirect { - ctx.Render.Redirect("/") + ctx.Redirect("/") return } ctx.Handle(200, "RepoAssignment", err) |