Example #1
0
func (r *StaticBinaryResult) Apply(req *revel.Request, resp *revel.Response) {
	// If we have a ReadSeeker, delegate to http.ServeContent
	if rs, ok := r.Reader.(io.ReadSeeker); ok {
		// http.ServeContent doesn't know about response.ContentType, so we set the respective header.
		if resp.ContentType != "" {
			resp.Out.Header().Set("Content-Type", resp.ContentType)
		} else {
			contentType := revel.ContentTypeByFilename(r.Name)
			resp.Out.Header().Set("Content-Type", contentType)
		}
		http.ServeContent(resp.Out, req.Request, r.Name, r.ModTime, rs)
	} else {
		// Else, do a simple io.Copy.
		if r.Length != -1 {
			resp.Out.Header().Set("Content-Length", strconv.FormatInt(r.Length, 10))
		}
		resp.WriteHeader(http.StatusOK, revel.ContentTypeByFilename(r.Name))
		io.Copy(resp.Out, r.Reader)
	}

	// Close the Reader if we can
	if v, ok := r.Reader.(io.Closer); ok {
		v.Close()
	}
}
Example #2
0
// 错误显示出
func (r ErrorResult) Apply(req *revel.Request, resp *revel.Response) {
	format := req.Format
	status := resp.Status
	if status == 0 {
		status = http.StatusInternalServerError
	}

	contentType := revel.ContentTypeByFilename("xxx." + format)
	if contentType == revel.DefaultFileContentType {
		contentType = "text/plain"
	}

	// Get the error template.
	var err error
	templatePath := fmt.Sprintf("errors/%d.%s", status, format)
	err = nil
	//	tmpl, err := revel.MainTemplateLoader.Template("index.html") // 这里找到错误页面主题

	// This func shows a plaintext error message, in case the template rendering
	// doesn't work.
	showPlaintext := func(err error) {
		revel.PlaintextErrorResult{fmt.Errorf("Server Error:\n%s\n\n"+
			"Additionally, an error occurred when rendering the error page:\n%s",
			r.Error, err)}.Apply(req, resp)
	}

	// 根据是否是preview来得到404模板
	// 是, 则显示系统的错误信息, blog-500.html
	var tmpl *template.Template
	if r.IsPreview {
		tmpl = r.CurBlogTpl.Template.Lookup("blog/404.html")
	} else {
		tmpl = r.CurBlogTpl.Template.Lookup("404.html")
	}
	if tmpl == nil {
		if err == nil {
			err = fmt.Errorf("Couldn't find template %s", templatePath)
		}
		showPlaintext(err)
		return
	}

	// If it's not a revel error, wrap it in one.
	var revelError *revel.Error
	switch e := r.Error.(type) {
	case *revel.Error:
		revelError = e
	case error:
		revelError = &revel.Error{
			Title:       "Server Error",
			Description: e.Error(),
		}
	}

	if revelError == nil {
		panic("no error provided")
	}

	if r.RenderArgs == nil {
		r.RenderArgs = make(map[string]interface{})
	}
	r.RenderArgs["Error"] = revelError
	r.RenderArgs["Router"] = revel.MainRouter

	// 不是preview就不要显示错误了
	if r.IsPreview {
		var b bytes.Buffer
		out := io.Writer(resp.Out)
		//	out = ioutil.Discard
		err = tmpl.Execute(&b, r.RenderArgs)
		resp.WriteHeader(http.StatusOK, "text/html; charset=utf-8")
		b.WriteTo(out)
	}
}