-
Notifications
You must be signed in to change notification settings - Fork 9
/
main.go
executable file
·132 lines (109 loc) · 2.25 KB
/
main.go
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 (
"bufio"
"fmt"
"io"
"math/rand"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
)
const DbFile = "data.db"
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
var host = ""
var keyLength = 4
func init() {
rand.Seed(time.Now().UnixNano())
host = os.Getenv("PASTR_HOST")
newKeyLength, err := strconv.Atoi(os.Getenv("PASTR_KEY_LENGTH"))
if err == nil && newKeyLength >= 4 && newKeyLength <= 12 {
keyLength = newKeyLength
}
}
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
defer r.Body.Close()
body, _ := io.ReadAll(r.Body)
key, err := setKey(string(body))
if err == nil {
fmt.Fprint(w, combine(host, key))
}
return
}
query := r.URL.Path[1:]
if query == "" {
http.ServeFile(w, r, "index.html")
return
}
value, err := getKey(query)
if err == nil && value != "" {
if isUrl(value) {
http.Redirect(w, r, value, http.StatusFound)
}
fmt.Fprint(w, value)
return
}
w.WriteHeader(http.StatusNotFound)
fmt.Fprint(w, "Not Found")
})
http.ListenAndServe(":3000", nil)
}
func getKey(key string) (string, error) {
file, err := os.Open(DbFile)
if err != nil {
return "", err
}
scanner := bufio.NewScanner(file)
for scanner.Scan() {
text := scanner.Text()
if strings.HasPrefix(text, key+" ") {
return text[len(key+" "):], scanner.Err()
}
}
return "", scanner.Err()
}
func setKey(value string) (string, error) {
file, err := os.OpenFile(DbFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return "", err
}
defer file.Close()
key := genKey()
for {
content, err := getKey(key)
if err != nil {
return "", err
}
if content == "" {
break
}
key = genKey()
}
_, err2 := file.WriteString(key + " " + value + "\n")
if err2 != nil {
return "", err2
}
return key, nil
}
func isUrl(value string) bool {
_, err := url.ParseRequestURI(value)
return err == nil
}
func combine(host string, key string) string {
url, err := url.JoinPath(host, key)
if err != nil {
return key
}
return url
}
func genKey() string {
bytes := make([]rune, keyLength)
for i := range bytes {
bytes[i] = letters[rand.Intn(len(letters))]
}
return string(bytes)
}