Initial structure

This commit is contained in:
Ian Gulliver
2024-11-26 15:04:05 -06:00
parent e0f227f7d9
commit 3eb8785440
3 changed files with 74 additions and 1 deletions

15
error.go Normal file
View File

@@ -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...)})
}

14
json.go Normal file
View File

@@ -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)
}

46
main.go
View File

@@ -3,6 +3,7 @@ package main
import ( import (
"database/sql" "database/sql"
"fmt" "fmt"
"html/template"
"log" "log"
"net/http" "net/http"
"os" "os"
@@ -10,6 +11,43 @@ import (
_ "github.com/lib/pq" _ "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() { func main() {
port := os.Getenv("PORT") port := os.Getenv("PORT")
if port == "" { if port == "" {
@@ -26,7 +64,6 @@ func main() {
log.Fatal(err) log.Fatal(err)
} }
// Execute the SQL statement
_, err = db.Exec(` _, err = db.Exec(`
CREATE TABLE IF NOT EXISTS links ( CREATE TABLE IF NOT EXISTS links (
short VARCHAR(100) PRIMARY KEY, short VARCHAR(100) PRIMARY KEY,
@@ -36,6 +73,13 @@ CREATE TABLE IF NOT EXISTS links (
log.Fatalf("Failed to create table: %v", err) 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) bind := fmt.Sprintf(":%s", port)
log.Printf("listening on %s", bind) log.Printf("listening on %s", bind)