diff options
author | Julien Dessaux | 2024-03-25 13:58:48 +0100 |
---|---|---|
committer | Julien Dessaux | 2024-03-25 13:58:48 +0100 |
commit | 4c9b51b8c6b2ebeea0481d219df89ed4fec1e360 (patch) | |
tree | 4fadf1fb8dc7de8de571d828ecf61014826d9e9e /main.go | |
parent | chore(dictionary): go mod init and initial dictionary (diff) | |
download | ods-4c9b51b8c6b2ebeea0481d219df89ed4fec1e360.tar.gz ods-4c9b51b8c6b2ebeea0481d219df89ed4fec1e360.tar.bz2 ods-4c9b51b8c6b2ebeea0481d219df89ed4fec1e360.zip |
feat(ods): implement basic ods functionality
Diffstat (limited to 'main.go')
-rw-r--r-- | main.go | 75 |
1 files changed, 75 insertions, 0 deletions
@@ -0,0 +1,75 @@ +package main + +import ( + "embed" + "html/template" + "log/slog" + "net/http" + "strings" +) + +// Variables to customise the search behaviour +const ( + listenStr = "0.0.0.0:8090" +) + +//go:embed ods.txt +var ods string + +//go:embed index.html +var templatesFS embed.FS + +//go:embed static/* +var static embed.FS + +// html templates +var indexTemplate = template.Must(template.New("index").ParseFS(templatesFS, "index.html")) + +type IndexData struct { + HasQuery bool + Query string + Invalid bool +} + +func getIndex() http.Handler { + data := IndexData{ + HasQuery: false, + Query: "", + Invalid: true, + } + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Cache-Control", "no-store, no-cache") + indexTemplate.ExecuteTemplate(w, "index.html", data) + }) +} + +func postIndex() http.Handler { + words := strings.Split(ods,"\n") + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + data := IndexData{ + HasQuery: true, + Query: r.FormValue("query"), + Invalid: true, + } + query := strings.ToUpper(data.Query) + for _, w := range words { + if w == query { + data.Invalid = false + break + } + } + w.Header().Set("Cache-Control", "no-store, no-cache") + indexTemplate.ExecuteTemplate(w, "index.html", data) + }) +} + +// The main function +func main() { + http.Handle("GET /static/", http.FileServer(http.FS(static))) + http.Handle("GET /", getIndex()) + http.Handle("POST /", postIndex()) + slog.Info("listening", "addr", listenStr) + if err := http.ListenAndServe(listenStr, nil); err != nil && err != http.ErrServerClosed { + slog.Error("error listening and serving", "error", err) + } +} |