-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.go
100 lines (85 loc) · 2.29 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
package main
import (
"github.com/Webbaum/w0q/config"
"github.com/Webbaum/w0q/models"
"github.com/fsuhrau/anonymizer"
"github.com/gin-gonic/gin"
"html/template"
"math/rand"
"net/http"
"time"
)
func RandStringBytesMask(n int) string {
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
b := make([]byte, n)
for i := range b {
b[i] = letterBytes[rand.Intn(len(letterBytes))]
}
return string(b)
}
func init() {
rand.Seed(time.Now().UTC().UnixNano())
}
func printAscii() {
var ascii string = "" +
" ___ ___________\n" +
" / _ \\ //_________/ \n" +
" __________| | | |_// _ \n" +
" \\\\ \\ /\\ / / | | |//_` |\n" +
" \\\\ V V /| |_| |/(_| |\n" +
" \\\\_/\\_/__\\___//\\__, |\n" +
" | |\n" +
" |_|\n"
print(ascii)
}
func main() {
r := gin.Default()
r.LoadHTMLFiles("public/legal.html")
config.ReadConfig()
models.ConnectDatabase()
// handle static files
r.StaticFile("/", "./public/index.html")
r.GET("/legal", func(c *gin.Context) {
c.HTML(http.StatusOK, "public/legal.html", gin.H{
"address": template.HTML(config.MyConfig.LegalAddress),
"mail": template.HTML(config.MyConfig.LegalMail),
"phone": template.HTML(config.MyConfig.LegalPhone),
})
})
r.StaticFile("/favicon.png", "./public/favicon.png")
r.StaticFile("/robots.txt", "./public/robots.txt")
r.StaticFile("/styles.css", "./public/styles.css")
r.POST("/url", func(c *gin.Context) {
var input models.UrlInput
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
var id string
for {
id = RandStringBytesMask(5)
var result = models.DB.First(&models.Url{}, "id = ?", id)
if result.RowsAffected == 0 {
break
}
}
url := models.Url{
ID: id,
Url: input.Url,
Date: time.Now(),
IP: anonymizer.AnonymizeIP(c.ClientIP()),
}
models.DB.Create(&url)
c.JSON(http.StatusOK, gin.H{"data": url})
})
r.GET("/:id", func(c *gin.Context) {
var url models.Url
if err := models.DB.First(&url, "id = ?", c.Param("id")).Error; err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "Record not found!"})
return
}
c.Redirect(http.StatusMovedPermanently, url.Url)
})
printAscii()
r.Run()
}