links.go
go
package controllers
import (
	"net/http"
	"strings"
	"theskyscape.com/repo/skykit"
	"theskyscape.com/repo/skylinks/models"
)
func Links() (string, skykit.Handler) {
	return "links", &LinksController{}
}
type LinksController struct {
	skykit.Controller
}
func (c *LinksController) Setup(app *skykit.Application) {
	c.Controller.Setup(app)
	models.SetUserLookup(app.Users.Get)
	http.Handle("/", c.Serve("home.html", nil))
	http.HandleFunc("POST /links", c.handleCreateLink)
	http.HandleFunc("DELETE /links/{link}", c.handleDeleteLink)
}
func (c LinksController) Handle(r *http.Request) skykit.Handler {
	c.Request = r
	return &c
}
func (c *LinksController) RecentLinks() []*models.Link {
	links, err := models.Links.Search("ORDER BY CreatedAt DESC")
	if err != nil {
		return nil
	}
	return links
}
func (c *LinksController) handleCreateLink(w http.ResponseWriter, r *http.Request) {
	if err := r.ParseForm(); err != nil {
		c.Render(w, r, "error-message.html", "Invalid form submission")
		return
	}
	user, _ := c.Users.Authenticate(r)
	target := strings.TrimSpace(r.FormValue("target_url"))
	short := strings.TrimSpace(r.FormValue("short_code"))
	if _, err := models.CreateLink(target, short, user); err != nil {
		c.Render(w, r, "error-message.html", err.Error())
		return
	}
	c.Refresh(w, r)
}
func (c *LinksController) handleDeleteLink(w http.ResponseWriter, r *http.Request) {
	link, err := models.Links.Get(r.PathValue("link"))
	if err != nil {
		w.Write([]byte("Link not found"))
		return
	}
	user, err := c.Users.Authenticate(r)
	if err != nil || !link.CanDelete(user) {
		w.Write([]byte("Not authenticated"))
		return
	}
	if err := models.Links.Delete(link); err != nil {
		w.Write([]byte("Unable to delete link"))
		return
	}
	c.Refresh(w, r)
}
No comments yet.