123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- package ui
- import (
- "fmt"
- "io"
- "log"
- "net/http"
- "strings"
- "github.com/gorilla/sessions"
- "code.osinet.fr/fgm/kurz/domain"
- "github.com/gorilla/mux"
- )
- // handlePostTarget handles form POST requests to /
- func handlePostTarget(w http.ResponseWriter, r *http.Request, router *mux.Router) {
- var sess *sessions.Session
- sess, storeErr := store.Get(r, globals.SessionName)
- if storeErr != nil {
- log.Fatal()
- w.WriteHeader(http.StatusInternalServerError)
- return
- }
- r.ParseForm()
- defer r.Body.Close()
- rawTarget := r.PostForm.Get(rootInputName)
- target, err := validateTarget(rawTarget)
- if err != nil {
- sess.AddFlash(err.Error())
- sess.Save(r, w)
- location, err := URLFromRoute(router, RouteGetRoot, nil)
- if err != nil {
- w.WriteHeader(http.StatusInternalServerError)
- return
- }
- w.Header().Set("Location", location)
- w.WriteHeader(http.StatusSeeOther)
- return
- }
- short, isNew, err := domain.GetShortURL(target, nil)
- if err != nil {
- w.WriteHeader(http.StatusInternalServerError)
- return
- }
- fqsu, err := URLFromRoute(router, RouteGetShort, map[string]string{"short": short})
- if err != nil {
- w.WriteHeader(http.StatusInternalServerError)
- return
- }
- sw := &strings.Builder{}
- var templateName string
- if isNew {
- templateName = "201"
- } else {
- templateName = "409"
- }
- defer sess.Save(r, w)
- data := struct {
- Flashes []interface{}
- FullyQualifiedShortURL string
- FullyQualifiedTargetURL string
- Globals
- }{
- sess.Flashes(),
- fqsu,
- target,
- globals,
- }
- err = tmpl.ExecuteTemplate(sw, templateName, data)
- if err != nil {
- fmt.Println(err)
- w.WriteHeader(http.StatusInternalServerError)
- return
- }
- if isNew {
- w.WriteHeader(http.StatusCreated)
- } else {
- w.WriteHeader(http.StatusConflict)
- }
- io.Copy(w, strings.NewReader(sw.String()))
- }
- func validateTarget(raw string) (string, error) {
- if raw == "" {
- return "", domain.MakeError(nil, domain.TargetInvalid.ID, "empty target")
- }
- // BUG(fgm): needs much more validation, starting with XSS.
- return raw, nil
- }
|