Source

PastebinGo / handlers_paste.go

Full commit
// handlers_paste
package main

import (
	//"fmt"
	"github.com/gorilla/schema"
	"net/http"
	"strconv"
)

//=============================================================================

// showPaste show specific paste (by it's ID)
func showPaste(wri http.ResponseWriter, req *http.Request, ctx *Context) (err error) {
	pasteId, err := strconv.ParseInt(req.URL.Query().Get(":id"), 10, 64)
	if err != nil {
		panic("Wrong conversion")
	}

	paste, err := getPasteById(pasteId, ctx)

	if err != nil {
		http.Redirect(wri, req, reverse("index"), http.StatusNotFound)
		return
	}

	paste.DisplayDatetime = paste.Datetime.Format("2006-01-02 15:04:05")

	if paste.Syntax == "no-highlight" {
		paste.Syntax = ""
	}

	return T("show.html").Execute(wri, map[string]interface{}{
		"paste": paste,
		"ctx":   ctx,
	})
}

func showNewPaste(wri http.ResponseWriter, req *http.Request, ctx *Context) (err error) {
	pasteId, err := strconv.ParseInt(req.URL.Query().Get(":id"), 10, 64)
	if err != nil {
		panic("Wrong conversion")
	}

	paste, err := getPasteById(pasteId, ctx)

	if err != nil {
		http.Redirect(wri, req, reverse("index"), http.StatusNotFound)
		return
	}

	paste.DisplayDatetime = paste.Datetime.Format("2006-01-02 15:04:05")

	if paste.Syntax == "no-highlight" {
		paste.Syntax = ""
	}

	newPasteUrl := "http://" + req.Host + reverse("showPaste", "id", pasteId)
	return T("show.html").Execute(wri, map[string]interface{}{
		"paste":    paste,
		"pasteUrl": url(newPasteUrl),
		"ctx":      ctx,
	})
}

func addPaste(wri http.ResponseWriter, req *http.Request, ctx *Context) (err error) {
	paste := NewPaste()
	req.ParseForm()
	pasteData := new(PasteForm)
	schema.NewDecoder().Decode(pasteData, req.Form)
	if pasteData.Title != "" {
		paste.Title = pasteData.Title
	}

	paste.Data = pasteData.Data
	if paste.Data == "" {
		http.Redirect(wri, req, reverse("index"), http.StatusNoContent)
		return
	}

	if ctx.User == nil {
		if pasteData.Author != "" {
			paste.Author = pasteData.Author
		}
	} else {
		paste.Author = ctx.User.Name
		paste.UserID = ctx.User.ID
	}
	paste.Protection = pasteData.Protection
	paste.Syntax = pasteData.Syntax
	paste.IP = req.RemoteAddr

	lastId, err := insertPaste(paste, ctx)

	if err != nil {
		http.Redirect(wri, req, reverse("index"), http.StatusInternalServerError)
		return
	}

	http.Redirect(wri, req, reverse("showNewPaste", "id", lastId, "new", "new"), http.StatusSeeOther)
	return err
}