Initial structure
This commit is contained in:
15
error.go
Normal file
15
error.go
Normal 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
14
json.go
Normal 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
46
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)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user