Files
backend/main.go

73 lines
1.8 KiB
Go

package main
import (
"TheAdversary/api"
"TheAdversary/config"
"TheAdversary/database"
"TheAdversary/server"
"fmt"
"github.com/gorilla/mux"
"html/template"
"net/http"
"path"
"path/filepath"
)
func main() {
r := mux.NewRouter()
r.StrictSlash(true)
var subrouter *mux.Router
if config.Prefix != "" {
subrouter = r.PathPrefix(config.Prefix).Subrouter()
} else {
subrouter = r
}
setupApi(subrouter)
setupFrontend(subrouter)
db, err := database.NewSqlite3Connection(config.DatabaseFile)
if err != nil {
panic(err)
}
database.SetGlobDB(db)
if err := http.ListenAndServe(fmt.Sprintf(":%s", config.ServerPort), r); err != nil {
panic(err)
}
}
func setupApi(r *mux.Router) {
r.HandleFunc("/api/login", api.Login).Methods(http.MethodPost)
r.HandleFunc("/api/authors", api.Authors).Methods(http.MethodGet)
r.HandleFunc("/api/tags", api.Tags).Methods(http.MethodGet)
r.HandleFunc("/api/recent", api.Recent).Methods(http.MethodGet)
r.HandleFunc("/api/search", api.Search).Methods(http.MethodGet)
r.HandleFunc("/api/article", api.Article).Methods(http.MethodPost, http.MethodPatch, http.MethodDelete)
r.HandleFunc("/api/assets", api.Assets).Methods(http.MethodGet, http.MethodPost, http.MethodDelete)
}
func setupFrontend(r *mux.Router) {
r.HandleFunc("/article/{article}", server.Article).Methods(http.MethodGet)
r.PathPrefix("/sass/").HandlerFunc(server.ServePath)
r.PathPrefix("/img/").HandlerFunc(server.ServePath)
landingpage := template.Must(template.ParseFiles(filepath.Join(config.FrontendDir, "html", "landingpage.gohtml")))
r.PathPrefix("/").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if path.Join(config.Prefix)+"/" == r.URL.Path {
if err := landingpage.Execute(w, config.PageBase); err != nil {
fmt.Println(err)
}
} else {
server.Error404(w, r)
}
})
}