package ui //go:generate gotext -srclang=en update -out=catalog.go -lang=fr,en import ( "fmt" "io" "log" "net/http" "strings" "code.osinet.fr/fgm/kurz/domain" "code.osinet.fr/fgm/kurz/web/i18n" "github.com/gorilla/mux" "github.com/gorilla/sessions" _ "golang.org/x/text/message" ) // 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() p := i18n.Printer(r) rawTarget := r.PostForm.Get(rootInputName) target, err := validateTarget(rawTarget) if err != nil { sess.AddFlash(p.Sprintf(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) 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(domain.TargetInvalidError, "empty target") } // BUG(fgm): needs much more validation, starting with XSS. return raw, nil }