-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
185 lines (153 loc) · 4.23 KB
/
main.go
File metadata and controls
185 lines (153 loc) · 4.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
package main
import (
"context"
"database/sql"
"embed"
"errors"
"flag"
"fmt"
"io/fs"
"log"
"math/rand"
"net/http"
"net/url"
"os"
"strings"
"time"
"github.com/labstack/echo/v4"
_ "github.com/lib/pq"
"github.com/uptrace/bun"
"github.com/uptrace/bun/dialect/pgdialect"
"github.com/uptrace/bun/dialect/sqlitedialect"
"github.com/uptrace/bun/driver/sqliteshim"
"github.com/uptrace/bun/schema"
)
const name = "url-shortener"
const version = "0.0.10"
var revision = "HEAD"
//go:embed assets
var assets embed.FS
type ShortURL struct {
bun.BaseModel `bun:"table:urls,alias:u"`
ID string `bun:"id,pk" json:"id"`
Original string `bun:"original,notnull" json:"original"`
CreatedAt time.Time `bun:"created_at,notnull" json:"created_at"`
}
type ShortURLRequest struct {
URL string `json:"url" validate:"required,url"`
}
type App struct {
db *bun.DB
}
type Response struct {
ShortURL string `json:"short_url,omitempty"`
Error string `json:"error,omitempty"`
}
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
func generateShortID(length int) string {
var sb strings.Builder
for i := 0; i < length; i++ {
sb.WriteByte(charset[rand.Intn(len(charset))])
}
return sb.String()
}
func (app *App) shortenURLHandler(c echo.Context) error {
var req ShortURLRequest
if err := c.Bind(&req); err != nil {
return c.JSON(http.StatusBadRequest, Response{Error: "Invalid request body"})
}
if !strings.HasPrefix(req.URL, "http://") && !strings.HasPrefix(req.URL, "https://") {
return c.JSON(http.StatusBadRequest, Response{Error: "Invalid URL"})
}
ctx := c.Request().Context()
var shortID string
for {
shortID = generateShortID(6)
var exists ShortURL
err := app.db.NewSelect().Model(&exists).Where("id = ?", shortID).Scan(ctx)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
return c.JSON(http.StatusInternalServerError, Response{Error: "Database error"})
}
if errors.Is(err, sql.ErrNoRows) {
break
}
}
shortURL := &ShortURL{
ID: shortID,
Original: req.URL,
CreatedAt: time.Now(),
}
_, err := app.db.NewInsert().Model(shortURL).Exec(ctx)
if err != nil {
log.Println(err)
return c.JSON(http.StatusInternalServerError, Response{Error: "Failed to save URL"})
}
serverURL := os.Getenv("SERVER_URL")
if serverURL == "" {
serverURL = "http://"
if c.Request().TLS != nil {
serverURL = "https://"
}
serverURL += c.Request().Host
}
log.Println("server", serverURL)
u, err := url.Parse(serverURL)
if err != nil {
log.Println(err)
return c.JSON(http.StatusInternalServerError, Response{Error: "Failed to save URL"})
}
u.Path = shortID
return c.JSON(http.StatusOK, Response{ShortURL: u.String()})
}
func (app *App) redirectHandler(c echo.Context) error {
shortID := c.Param("id")
ctx := c.Request().Context()
var url ShortURL
err := app.db.NewSelect().Model(&url).Where("id = ?", shortID).Scan(ctx)
if errors.Is(err, sql.ErrNoRows) {
return c.JSON(http.StatusNotFound, Response{Error: "Short URL not found"})
} else if err != nil {
return c.JSON(http.StatusInternalServerError, Response{Error: "Database error"})
}
return c.Redirect(http.StatusMovedPermanently, url.Original)
}
func main() {
var ver bool
flag.BoolVar(&ver, "version", false, "show version")
flag.Parse()
if ver {
fmt.Println(version)
os.Exit(0)
}
dsn := os.Getenv("DATABASE_URL")
driver := sqliteshim.ShimName
var dialect schema.Dialect = sqlitedialect.New()
if dsn == "" {
dsn = "file:./url-shortener.sqlite"
}
if strings.HasPrefix(dsn, "postgres://") {
driver = "postgres"
dialect = pgdialect.New()
}
db, err := sql.Open(driver, dsn)
if err != nil {
log.Fatal(err)
}
bundb := bun.NewDB(db, dialect)
defer bundb.Close()
_, err = bundb.NewCreateTable().Model((*ShortURL)(nil)).IfNotExists().Exec(context.Background())
if err != nil {
log.Fatal(err)
}
app := &App{db: bundb}
e := echo.New()
e.POST("/shorten", app.shortenURLHandler)
e.GET("/:id", app.redirectHandler)
sub, _ := fs.Sub(assets, "assets")
e.GET("/", echo.WrapHandler(http.FileServer(http.FS(sub))))
e.GET("/static/*", echo.WrapHandler(http.FileServer(http.FS(sub))))
log.Println("Server starting on :8080")
if err := e.Start(":8080"); err != nil {
fmt.Printf("Server failed: %v\n", err)
}
}