Moved away from local files to complete database driven articles

This commit is contained in:
2021-12-20 23:10:04 +01:00
parent bc3ec64b3c
commit c909339a73
20 changed files with 302 additions and 299 deletions

View File

@@ -2,33 +2,28 @@ package server
import (
"TheAdversary/database"
"TheAdversary/parse"
"database/sql"
"fmt"
"github.com/gorilla/mux"
"net/http"
)
// var tmpl = template.Must(template.ParseFiles(config.ArticleTemplate))
func Article(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
articleName := mux.Vars(r)["article"]
article, err := database.GetDB().GetArticleByName(articleName)
if err != nil {
if err == sql.ErrNoRows {
w.WriteHeader(http.StatusNotFound)
Error404(w, r)
} else {
w.WriteHeader(http.StatusInternalServerError)
Error500(w, r)
}
return
}
parsed, _ := parse.ParseToHtml(article)
if len(parsed) > 0 {
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, string(parsed))
} else {
w.WriteHeader(http.StatusNotFound)
}
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, article.Html)
}

25
server/error.go Normal file
View File

@@ -0,0 +1,25 @@
package server
import (
"TheAdversary/config"
"io"
"log"
"net/http"
"path/filepath"
)
func init() {
// disable default log output because http.ServeFile prints
// a message if a header is written 2 times or more
log.Default().SetOutput(io.Discard)
}
func Error404(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
http.ServeFile(w, r, filepath.Join(config.FrontendDir, "error", "404.html"))
}
func Error500(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
http.ServeFile(w, r, filepath.Join(config.FrontendDir, "error", "500.html"))
}

17
server/path.go Normal file
View File

@@ -0,0 +1,17 @@
package server
import (
"TheAdversary/config"
"net/http"
"os"
"path/filepath"
)
func ServePath(w http.ResponseWriter, r *http.Request) {
path := filepath.Join(config.FrontendDir, r.URL.Path)
if _, err := os.Stat(path); os.IsNotExist(err) {
Error404(w, r)
} else {
http.ServeFile(w, r, path)
}
}