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 }