88 lines
1.7 KiB
Go
88 lines
1.7 KiB
Go
|
package handlers
|
||
|
|
||
|
import (
|
||
|
"court/database"
|
||
|
"court/models"
|
||
|
"fmt"
|
||
|
"html/template"
|
||
|
"net/http"
|
||
|
)
|
||
|
|
||
|
var (
|
||
|
DB *database.DB
|
||
|
BaseURL string
|
||
|
)
|
||
|
|
||
|
func SetupDB() error {
|
||
|
var err error
|
||
|
err, DB = database.ConnectDB()
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
func Redirect(w http.ResponseWriter, r *http.Request) {
|
||
|
id := r.PathValue("id")
|
||
|
err, url := DB.GetUrlByID(id)
|
||
|
if err != nil {
|
||
|
w.WriteHeader(http.StatusInternalServerError)
|
||
|
w.Write([]byte("Internal server error"))
|
||
|
return
|
||
|
}
|
||
|
if url == "" {
|
||
|
w.WriteHeader(http.StatusNotFound)
|
||
|
w.Write([]byte("Not Found"))
|
||
|
return
|
||
|
}
|
||
|
http.Redirect(w, r, url, http.StatusSeeOther)
|
||
|
}
|
||
|
|
||
|
func Delete(w http.ResponseWriter, r *http.Request) {
|
||
|
id := r.PathValue("id")
|
||
|
_, status := DB.DeleteByID(id)
|
||
|
if status == 500 {
|
||
|
w.WriteHeader(http.StatusInternalServerError)
|
||
|
w.Write([]byte("Internal server error"))
|
||
|
} else if status == 404 {
|
||
|
w.WriteHeader(http.StatusNotFound)
|
||
|
w.Write([]byte("Not Found"))
|
||
|
} else {
|
||
|
fmt.Fprint(w, "")
|
||
|
}
|
||
|
|
||
|
}
|
||
|
|
||
|
func Post(w http.ResponseWriter, r *http.Request) {
|
||
|
r.ParseForm()
|
||
|
|
||
|
id := r.FormValue("id")
|
||
|
url := r.FormValue("url")
|
||
|
|
||
|
tmpl := template.Must(template.ParseFiles("templates/fragments/link.html"))
|
||
|
if url == "" {
|
||
|
w.WriteHeader(http.StatusBadRequest)
|
||
|
w.Write([]byte("Bad Request"))
|
||
|
return
|
||
|
}
|
||
|
if id == "" {
|
||
|
err, randid := DB.CreateRandUrl(url)
|
||
|
if err != nil {
|
||
|
w.WriteHeader(http.StatusInternalServerError)
|
||
|
w.Write([]byte("Internal server error"))
|
||
|
return
|
||
|
}
|
||
|
tmpl.Execute(w, &models.Link{BaseUrl: BaseURL, ID: randid})
|
||
|
|
||
|
} else {
|
||
|
err, getid := DB.CreateChosenUrl(id, url)
|
||
|
if err != nil {
|
||
|
w.WriteHeader(http.StatusInternalServerError)
|
||
|
w.Write([]byte("Internal server error"))
|
||
|
return
|
||
|
}
|
||
|
tmpl.Execute(w, &models.Link{BaseUrl: BaseURL, ID: getid})
|
||
|
|
||
|
}
|
||
|
}
|