package pages import ( "bytes" "fmt" "git.binarythought.com/cdramey/qurl/obj" "net" "net/http" "time" ) type submitPage struct { Message string URL string } func (ctx *RootHandler) ServeSubmit(w http.ResponseWriter, r *http.Request) { var pg submitPage u := r.FormValue("url") if u == "" { pg.Message = "Not a valid URL." } else { q, err := ctx.Storage.GetQURLByURL(u) if err != nil { http.Error(w, fmt.Sprintf("Database error: %s", err.Error()), http.StatusInternalServerError) return } if q != nil { pg.Message = "URL already exists." pg.URL = fmt.Sprintf("https://qurl.org/%s", obj.ToString(q.ID)) } else { q = &obj.QURL{ URL: u, Created: time.Now(), } if h, _, err := net.SplitHostPort(r.RemoteAddr); err == nil && h != "" { q.IP = net.ParseIP(h) } if b := r.Header.Get("User-Agent"); b != "" { q.Browser = b } err := q.CheckValid() if err != nil { pg.Message = err.Error() } else { err := ctx.Storage.AddQURL(q) if err != nil { http.Error(w, fmt.Sprintf("Database error: %s", err.Error()), http.StatusInternalServerError) return } pg.Message = "URL Added." pg.URL = fmt.Sprintf("https://qurl.org/%s", obj.ToString(q.ID)) } } } var buf bytes.Buffer err := ctx.submit.Execute(&buf, pg) if err != nil { http.Error(w, fmt.Sprintf("Template execute error: %s", err.Error()), http.StatusInternalServerError) return } w.Header().Set("Content-Length", fmt.Sprintf("%d", buf.Len())) w.Header().Set("Content-Type", "text/html") w.Write(buf.Bytes()) }