2018-11-17 07:47:39 -09:00
|
|
|
package pages
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"fmt"
|
|
|
|
"html/template"
|
|
|
|
"net/http"
|
|
|
|
"qurl/qurl"
|
|
|
|
"qurl/static"
|
|
|
|
"qurl/storage"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
type SubmitHandler struct {
|
|
|
|
Storage storage.Storage
|
|
|
|
template *template.Template
|
|
|
|
}
|
|
|
|
|
|
|
|
type submitPage struct {
|
|
|
|
Message string
|
|
|
|
URL string
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ctx *SubmitHandler) Init() error {
|
|
|
|
ctx.template = template.New("submit.html")
|
|
|
|
|
|
|
|
_, err := ctx.template.Parse(string(static.Assets["submit.html"]))
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ctx *SubmitHandler) ServeHTTP(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", qurl.ToString(q.ID))
|
|
|
|
} else {
|
|
|
|
q = &qurl.QURL{
|
|
|
|
URL: u,
|
|
|
|
Created: time.Now(),
|
|
|
|
}
|
|
|
|
|
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."
|
|
|
|
pg.URL = fmt.Sprintf("https://qurl.org/%s", qurl.ToString(q.ID))
|
|
|
|
}
|
2018-11-17 07:47:39 -09:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
var buf bytes.Buffer
|
|
|
|
err := ctx.template.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())
|
|
|
|
}
|