Add search functionality

This commit is contained in:
ChaoticByte 2024-08-28 19:49:23 +02:00
parent 149841bdd1
commit 85470a277e
No known key found for this signature in database
8 changed files with 138 additions and 24 deletions

25
main.go
View file

@ -5,6 +5,7 @@ import (
"log"
"net/http"
"os"
"path"
"strings"
)
@ -28,16 +29,13 @@ func loadTemplate() {
func handleApplication(w http.ResponseWriter, req *http.Request) {
var entry string
var err error
entryName := strings.Trim(req.URL.Path, "/")
if entryName != "" {
if strings.Contains(entryName, "/") || strings.Contains(entryName, "..") {
// path traversal
logger.Println("Possible path traversal attempt from", req.RemoteAddr, "to", entryName)
w.WriteHeader(http.StatusForbidden)
return
}
entryName := path.Base(req.URL.Path)
if entryName != "/" {
// load entry
entry = db.Entries[entryName]
if entry == "" { // redirect if entry doesn't exist (or is empty)
http.Redirect(w, req, "/", http.StatusTemporaryRedirect)
}
}
err = appTemplate.ExecuteTemplate(
w, "app",
@ -45,6 +43,16 @@ func handleApplication(w http.ResponseWriter, req *http.Request) {
if err != nil { logger.Println(err) }
}
func handleSearchAPI(w http.ResponseWriter, req *http.Request) {
searchQuery := path.Base(req.URL.Path)
if searchQuery == "" {
w.WriteHeader(http.StatusBadRequest)
return
}
results := db.search(searchQuery)
w.Write([]byte(strings.Join(results, "\n")))
}
func main() {
// get logger
logger = log.Default()
@ -57,6 +65,7 @@ func main() {
http.Handle("/static/", staticHandler)
// handle application
http.HandleFunc("/", handleApplication)
http.HandleFunc("/search/", handleSearchAPI)
// start server
logger.Println("Starting server on", ServerListen)
err := http.ListenAndServe(ServerListen, nil)