From 3eb878544017162ac8869577f41892cb6ccd8169 Mon Sep 17 00:00:00 2001 From: Ian Gulliver Date: Tue, 26 Nov 2024 15:04:05 -0600 Subject: [PATCH] Initial structure --- error.go | 15 +++++++++++++++ json.go | 14 ++++++++++++++ main.go | 46 +++++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 74 insertions(+), 1 deletion(-) create mode 100644 error.go create mode 100644 json.go diff --git a/error.go b/error.go new file mode 100644 index 0000000..2de889d --- /dev/null +++ b/error.go @@ -0,0 +1,15 @@ +package main + +import ( + "fmt" + "net/http" +) + +type Error struct { + Message string `json:"message"` +} + +func sendError(w http.ResponseWriter, code int, msg string, args ...any) { + w.WriteHeader(code) + sendJSON(w, Error{Message: fmt.Sprintf(msg, args...)}) +} diff --git a/json.go b/json.go new file mode 100644 index 0000000..cfe3eae --- /dev/null +++ b/json.go @@ -0,0 +1,14 @@ +package main + +import ( + "encoding/json" + "net/http" +) + +func sendJSON(w http.ResponseWriter, v any) { + w.Header().Set("Content-Type", "application/json") + + enc := json.NewEncoder(w) + enc.SetEscapeHTML(false) + _ = enc.Encode(v) +} diff --git a/main.go b/main.go index bd41bcd..20d5942 100644 --- a/main.go +++ b/main.go @@ -3,6 +3,7 @@ package main import ( "database/sql" "fmt" + "html/template" "log" "net/http" "os" @@ -10,6 +11,43 @@ import ( _ "github.com/lib/pq" ) +type ShortLinks struct { + tmpl *template.Template + mux *http.ServeMux +} + +func NewShortLinks() (*ShortLinks, error) { + tmpl := template.New("index.html") + + tmpl, err := tmpl.ParseFiles("static/index.html") + if err != nil { + return nil, fmt.Errorf("static/index.html: %w", err) + } + + sl := &ShortLinks{ + tmpl: tmpl, + mux: http.NewServeMux(), + } + + sl.mux.HandleFunc("/", sl.serveRoot) + + return sl, nil +} + +func (sl *ShortLinks) ServeHTTP(w http.ResponseWriter, r *http.Request) { + sl.mux.ServeHTTP(w, r) +} + +func (sl *ShortLinks) serveRoot(w http.ResponseWriter, r *http.Request) { + log.Printf("%s %s", r.RemoteAddr, r.URL.Path) + + err := sl.tmpl.Execute(w, nil) + if err != nil { + sendError(w, http.StatusInternalServerError, "error executing template: %s", err) + return + } +} + func main() { port := os.Getenv("PORT") if port == "" { @@ -26,7 +64,6 @@ func main() { log.Fatal(err) } - // Execute the SQL statement _, err = db.Exec(` CREATE TABLE IF NOT EXISTS links ( short VARCHAR(100) PRIMARY KEY, @@ -36,6 +73,13 @@ CREATE TABLE IF NOT EXISTS links ( log.Fatalf("Failed to create table: %v", err) } + sl, err := NewShortLinks() + if err != nil { + log.Fatalf("Failed to create shortlinks: %v", err) + } + + http.Handle("/", sl) + bind := fmt.Sprintf(":%s", port) log.Printf("listening on %s", bind)