123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106 |
- package ui
- import (
- "fmt"
- "io"
- "log"
- "net/http"
- "strings"
- kurzi18n "code.osinet.fr/fgm/kurz/web/i18n"
- i18n "github.com/nicksnyder/go-i18n/v2/i18n"
- "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)
- localizer := kurzi18n.Localizer(r)
- target, err := validateTarget(rawTarget, localizer)
- 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, localizer)
- 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, localizer *i18n.Localizer) (string, error) {
- if raw == "" {
- detail := localizer.MustLocalize(&i18n.LocalizeConfig{
- DefaultMessage: &i18n.Message{
- ID: "web.ui.empty.target",
- Other: "empty target",
- },
- })
- return "", domain.MakeError(localizer, domain.TargetInvalid.ID, detail)
- }
- // BUG(fgm): needs much more validation, starting with XSS.
- return raw, nil
- }
|