aboutsummaryrefslogtreecommitdiff
path: root/server/main.go
blob: 92bce1ddeb08c91260b88478ae80e1052c361d6e (plain)
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
package main

import (
	"database/sql"
	"embed"
	"flag"
	"log"
	"math/rand"
	"net/http"

	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
	_ "github.com/mattn/go-sqlite3"
)

var (
	db             *sql.DB
	dbFilePath     string
	port           string
	shortIDCharset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
	shortIDLength  = 8
)

type Bin struct {
	Content  string `json:"content"`
	Language string `json:"language"`
	IV       string `json:"iv"`
}

const (
	insertQuery = "INSERT INTO bins (id, content, language, iv) VALUES (?, ?, ?, ?)"
	selectQuery = "SELECT content, language, iv FROM bins WHERE id = ?"
)

//go:embed all:dist
var dist embed.FS

func RegisterHandlers(e *echo.Echo) {
	e.Use(middleware.StaticWithConfig(middleware.StaticConfig{
		Root:       "dist",
		Index:      "index.html",
		HTML5:      true,
		Filesystem: http.FS(dist),
	}))
	e.Use(middleware.CORS())
	e.POST("/bin", postBin)
	e.GET("/bin/:id", getBin)
	e.GET("/r/:id", redirectToURL)
}

func main() {
	flag.StringVar(&port, "port", "8080", "HTTP server port")
	flag.StringVar(&dbFilePath, "db", "minibin.db", "Path to SQLite database file")
	flag.Parse()

	initDatabase()

	e := echo.New()
	RegisterHandlers(e)
	e.Logger.Fatal(e.Start(":" + port))
}

func initDatabase() {
	var err error
	db, err = sql.Open("sqlite3", dbFilePath)
	if err != nil {
		log.Fatal(err)
	}

	if err := createTable(); err != nil {
		log.Fatal(err)
	}
}

func postBin(c echo.Context) error {
	var bin Bin
	if err := c.Bind(&bin); err != nil {
		return err
	}

	id := generateShortID()
	if err := saveBin(id, bin); err != nil {
		return err
	}

	return c.JSON(http.StatusCreated, echo.Map{"id": id})
}

func getBin(c echo.Context) error {
	id := c.Param("id")
	bin, err := getBinByID(id)
	if err != nil {
		return err
	}
	return c.JSON(http.StatusOK, bin)
}

func redirectToURL(c echo.Context) error {
	id := c.Param("id")
	bin, err := getBinByID(id)
	if err != nil {
		c.Logger().Error(err)
		return err
	}

	return c.Redirect(http.StatusFound, bin.Content)
}

func createTable() error {
	_, err := db.Exec("CREATE TABLE IF NOT EXISTS bins (id TEXT PRIMARY KEY, content TEXT, language TEXT, iv TEXT)")
	return err
}

func getBinByID(id string) (Bin, error) {
	var bin Bin
	row := db.QueryRow(selectQuery, id)
	err := row.Scan(&bin.Content, &bin.Language, &bin.IV)
	return bin, err
}

func saveBin(id string, bin Bin) error {
	_, err := db.Exec(insertQuery, id, bin.Content, bin.Language, bin.IV)
	return err
}

func generateShortID() string {
	id := make([]byte, shortIDLength)
	for i := range id {
		id[i] = shortIDCharset[rand.Intn(len(shortIDCharset))]
	}
	return string(id)
}