2018-11-17 07:47:39 -09:00
|
|
|
package pages
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"fmt"
|
2019-12-26 07:21:48 -09:00
|
|
|
"git.binarythought.com/cdramey/qurl/obj"
|
2018-11-17 16:27:51 -09:00
|
|
|
"net"
|
2018-11-17 20:28:02 -09:00
|
|
|
"net/http"
|
2018-11-17 07:47:39 -09:00
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
type submitPage struct {
|
|
|
|
Message string
|
|
|
|
URL string
|
|
|
|
}
|
|
|
|
|
2018-11-17 20:28:02 -09:00
|
|
|
func (ctx *RootHandler) ServeSubmit(w http.ResponseWriter, r *http.Request) {
|
2018-11-17 07:47:39 -09:00
|
|
|
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."
|
2019-12-26 07:21:48 -09:00
|
|
|
pg.URL = fmt.Sprintf("https://qurl.org/%s", obj.ToString(q.ID))
|
2018-11-17 07:47:39 -09:00
|
|
|
} else {
|
2019-12-26 07:21:48 -09:00
|
|
|
q = &obj.QURL{
|
2018-11-17 07:47:39 -09:00
|
|
|
URL: u,
|
|
|
|
Created: time.Now(),
|
|
|
|
}
|
2018-11-17 16:27:51 -09:00
|
|
|
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
|
|
|
|
}
|
2018-11-17 07:47:39 -09:00
|
|
|
|
2018-11-17 08:07:33 -09:00
|
|
|
err := q.CheckValid()
|
2018-11-17 07:47:39 -09:00
|
|
|
if err != nil {
|
2018-11-17 08:07:33 -09:00
|
|
|
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
|
|
|
|
}
|
2018-11-17 07:47:39 -09:00
|
|
|
|
2018-11-17 08:07:33 -09:00
|
|
|
pg.Message = "URL Added."
|
2019-12-26 07:21:48 -09:00
|
|
|
pg.URL = fmt.Sprintf("https://qurl.org/%s", obj.ToString(q.ID))
|
2018-11-17 08:07:33 -09:00
|
|
|
}
|
2018-11-17 07:47:39 -09:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
var buf bytes.Buffer
|
2018-11-17 20:28:02 -09:00
|
|
|
err := ctx.submit.Execute(&buf, pg)
|
2018-11-17 07:47:39 -09:00
|
|
|
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())
|
|
|
|
}
|