Files
x/main.go

90 lines
1.6 KiB
Go
Raw Normal View History

2024-11-24 21:36:03 -06:00
package main
import (
2024-11-24 22:05:22 -06:00
"database/sql"
2024-11-24 21:36:03 -06:00
"fmt"
2024-11-26 15:04:05 -06:00
"html/template"
2024-11-24 21:36:03 -06:00
"log"
"net/http"
"os"
2024-11-24 22:05:22 -06:00
_ "github.com/lib/pq"
2024-11-24 21:36:03 -06:00
)
2024-11-26 15:04:05 -06:00
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
}
}
2024-11-24 21:36:03 -06:00
func main() {
port := os.Getenv("PORT")
if port == "" {
2024-11-24 22:05:22 -06:00
log.Fatalf("please set PORT")
}
pgConn := os.Getenv("PGCONN")
if pgConn == "" {
log.Fatalf("please set PGCONN")
}
2024-11-25 10:21:25 -06:00
db, err := sql.Open("postgres", pgConn)
2024-11-24 22:05:22 -06:00
if err != nil {
log.Fatal(err)
2024-11-24 21:36:03 -06:00
}
2024-11-25 10:21:25 -06:00
_, err = db.Exec(`
CREATE TABLE IF NOT EXISTS links (
short VARCHAR(100) PRIMARY KEY,
long VARCHAR(255) NOT NULL
);`)
if err != nil {
log.Fatalf("Failed to create table: %v", err)
}
2024-11-26 15:04:05 -06:00
sl, err := NewShortLinks()
if err != nil {
log.Fatalf("Failed to create shortlinks: %v", err)
}
http.Handle("/", sl)
2024-11-24 21:36:03 -06:00
bind := fmt.Sprintf(":%s", port)
log.Printf("listening on %s", bind)
if err := http.ListenAndServe(bind, nil); err != nil {
log.Fatalf("listen: %s", err)
}
}