Compare commits

...

3 commits

2 changed files with 10 additions and 4 deletions

View file

@ -6,4 +6,5 @@
Environmental variables:
- `SHORTEN_HOST` - hostname
- `POSTGRES_URI` - lib/pq connection string (see [here](https://pkg.go.dev/github.com/lib/pq#section-documentation))
- `SHORTEN_BIND` - bind address (default: `127.0.0.1:4488`)
- `POSTGRES_URI` - lib/pq connection string (see [here](https://pkg.go.dev/github.com/lib/pq#section-documentation))

11
main.go
View file

@ -12,6 +12,7 @@ import (
"time"
"database/sql"
"github.com/asaskevich/govalidator"
_ "github.com/lib/pq"
)
@ -70,7 +71,11 @@ func main() {
panic(err)
}
panic(http.ListenAndServe("127.0.0.1:4488", &Handler{db: db}))
bind := os.Getenv("SHORTEN_BIND")
if bind == "" {
bind = "127.0.0.1:4488"
}
panic(http.ListenAndServe(bind, &Handler{db: db}))
}
type Handler struct {
@ -119,7 +124,7 @@ func (h *Handler) CreateHandler(wr http.ResponseWriter, req *http.Request) {
}
req.ParseForm()
code, err := h.GetCode(req.Form.Get("url"), req.RemoteAddr)
code, err := h.GetCode(req.Form.Get("url"), ip)
if err != nil {
Render(wr, map[string]string{"error": err.Error()})
} else {
@ -143,7 +148,7 @@ func (h *Handler) RedirectHandler(wr http.ResponseWriter, req *http.Request) {
}
go func() {
_, _ = h.db.Exec(`UPDATE urls SET hits = $1 WHERE code = $2`, hits + 1, code)
_, _ = h.db.Exec(`UPDATE urls SET hits = $1 WHERE code = $2`, hits+1, code)
}()
wr.Header().Set("Location", url)