Compare commits

..

No commits in common. "d5fea7058738954b38f3751939027cc89efc5d2c" and "df2b918801e04d58e162498bb9b6bb700dfee82e" have entirely different histories.

19 changed files with 356 additions and 561 deletions

7
.env
View file

@ -1,6 +1,7 @@
PLAKKEN_LISTEN=:3000 PLAKKEN_INTERFACE=0.0.0.0
PLAKKEN_REDIS_ADDRESS=localhost:6379 PLAKKEN_PORT=3000
PLAKKEN_REDIS_ADDR=localhost:6379
PLAKKEN_REDIS_USER= PLAKKEN_REDIS_USER=
PLAKKEN_REDIS_PASSWORD= PLAKKEN_REDIS_PASSWORD=
PLAKKEN_REDIS_DB=0 PLAKKEN_REDIS_DB=0
PLAKKEN_URL_LENGTH=5 PLAKKEN_REDIS_URL_LEN=5

4
.gitignore vendored
View file

@ -1,7 +1,3 @@
# IDE specific
.idea
.vscode
### Go ### ### Go ###
*.exe *.exe
*.exe~ *.exe~

54
config.go Normal file
View file

@ -0,0 +1,54 @@
package main
import (
"github.com/joho/godotenv"
"log"
"os"
"strconv"
)
type Config struct {
host string
port string
redisAddr string
redisUser string
redisPassword string
redisDB int
urlLength int
}
func GetConfig() Config {
err := godotenv.Load()
if err != nil {
log.Fatalf("Error loading .env file: %v", err)
}
port := os.Getenv("PLAKKEN_PORT")
redisAddr := os.Getenv("PLAKKEN_REDIS_ADDR")
db := os.Getenv("PLAKKEN_REDIS_DB")
uLen := os.Getenv("PLAKKEN_REDIS_URL_LEN")
if port == "" || redisAddr == "" {
log.Fatal("Missing or invalid PLAKKEN_PORT or PLAKKEN_REDIS_ADDR")
}
redisDB, err := strconv.Atoi(db)
if err != nil {
log.Fatal("Invalid PLAKKEN_REDIS_DB")
}
urlLen, err := strconv.Atoi(uLen)
if err != nil {
log.Fatal("Invalid PLAKKEN_REDIS_URL_LEN")
}
return Config{
host: os.Getenv("PLAKKEN_INTERFACE"),
port: port,
redisAddr: redisAddr,
redisUser: os.Getenv("PLAKKEN_REDIS_USER"),
redisPassword: os.Getenv("PLAKKEN_REDIS_PASSWORD"),
redisDB: redisDB,
urlLength: urlLen,
}
}

49
db.go Normal file
View file

@ -0,0 +1,49 @@
package main
import (
"context"
"log"
"time"
"github.com/redis/go-redis/v9"
)
var ctx = context.Background()
func ConnectDB() *redis.Client {
localDb := redis.NewClient(&redis.Options{
Addr: currentConfig.redisAddr,
Username: currentConfig.redisUser,
Password: currentConfig.redisPassword,
DB: currentConfig.redisDB,
})
return localDb
}
func insertPaste(key string, content string, secret string, ttl time.Duration) {
type dbSchema struct {
content string
secret string
}
hash := dbSchema{
content: content,
secret: secret,
}
err := db.HSet(ctx, key, "content", hash.content)
if err != nil {
log.Println(err)
}
err = db.HSet(ctx, key, "secret", hash.secret)
if ttl > -1 {
db.Expire(ctx, key, ttl)
}
}
func getContent(key string) string {
return db.HGet(ctx, key, "content").Val()
}
func DeleteContent(key string) {
db.Del(ctx, key)
}

4
go.mod
View file

@ -1,6 +1,6 @@
module git.gnous.eu/gnouseu/plakken module plakken
go 1.22 go 1.21
require ( require (
github.com/joho/godotenv v1.5.1 github.com/joho/godotenv v1.5.1

View file

@ -1,59 +0,0 @@
package config
import (
"log"
"os"
"strconv"
"github.com/joho/godotenv"
)
// InitConfig Structure for program initialisation
type InitConfig struct {
ListenAddress string
RedisAddress string
RedisUser string
RedisPassword string
RedisDB int
UrlLength uint8
}
// GetConfig Initialise configuration form .env
func GetConfig() InitConfig {
err := godotenv.Load()
if err != nil {
log.Fatalf("Error loading .env file: %v", err)
}
listenAddress := os.Getenv("PLAKKEN_LISTEN")
redisAddress := os.Getenv("PLAKKEN_REDIS_ADDRESS")
db := os.Getenv("PLAKKEN_REDIS_DB")
uLen := os.Getenv("PLAKKEN_URL_LENGTH")
if listenAddress == "" || redisAddress == "" {
log.Fatal("Missing or invalid listenAddress or PLAKKEN_REDIS_ADDRESS")
}
redisDB, err := strconv.Atoi(db)
if err != nil {
log.Fatal("Invalid PLAKKEN_REDIS_DB")
}
urlLength, err := strconv.Atoi(uLen)
if err != nil {
log.Fatal("Invalid PLAKKEN_URL_LENGTH")
}
if urlLength > 255 {
log.Fatal("PLAKKEN_URL_LENGTH cannot be greater than 255")
}
return InitConfig{
ListenAddress: listenAddress,
RedisAddress: redisAddress,
RedisUser: os.Getenv("PLAKKEN_REDIS_USER"),
RedisPassword: os.Getenv("PLAKKEN_REDIS_PASSWORD"),
RedisDB: redisDB,
UrlLength: uint8(urlLength),
}
}

View file

@ -1,7 +0,0 @@
package constant
import "time"
const (
HTTPTimeout = 3 * time.Second
)

View file

@ -1,64 +0,0 @@
package database
import (
"context"
"log"
"time"
"github.com/redis/go-redis/v9"
)
type DBConfig struct {
DB *redis.Client
}
var ctx = context.Background()
// InitDB initialise redis connection settings
func InitDB(addr string, user string, password string, db int) *redis.Options {
DBConfig := &redis.Options{
Addr: addr,
Username: user,
Password: password,
DB: db,
}
return DBConfig
}
// ConnectDB make new database connection
func ConnectDB(dbConfig *redis.Options) *redis.Client {
localDb := redis.NewClient(dbConfig)
return localDb
}
func (config DBConfig) InsertPaste(key string, content string, secret string, ttl time.Duration) {
type dbSchema struct {
content string
secret string
}
hash := dbSchema{
content: content,
secret: secret,
}
err := config.DB.HSet(ctx, key, "content", hash.content).Err()
if err != nil {
log.Println(err)
}
err = config.DB.HSet(ctx, key, "secret", hash.secret).Err()
if err != nil {
log.Println(err)
}
if ttl > -1 {
config.DB.Expire(ctx, key, ttl)
}
}
func (config DBConfig) UrlExist(url string) bool {
return config.DB.Exists(ctx, url).Val() == 1
}
func (config DBConfig) VerifySecret(url string, secret string) bool {
return secret == config.DB.HGet(ctx, url, "secret").Val()
}

View file

@ -1,51 +0,0 @@
package httpServer
import (
"log"
"net/http"
"git.gnous.eu/gnouseu/plakken/internal/constant"
"git.gnous.eu/gnouseu/plakken/internal/web/plak"
"git.gnous.eu/gnouseu/plakken/internal/web/static"
"github.com/redis/go-redis/v9"
)
type ServerConfig struct {
HTTPServer *http.Server
UrlLength uint8
DB *redis.Client
}
// Configure HTTP router
func (config ServerConfig) router(_ http.ResponseWriter, _ *http.Request) {
WebConfig := plak.WebConfig{
DB: config.DB,
UrlLength: config.UrlLength,
}
http.HandleFunc("GET /{$}", static.Home)
http.HandleFunc("GET /{key}/{settings...}", WebConfig.View)
http.HandleFunc("GET /static/{file}", static.ServeStatic)
http.HandleFunc("POST /{$}", WebConfig.Create)
http.HandleFunc("DELETE /{key}", WebConfig.Delete)
}
// Config Configure HTTP server
func Config(listenAddress string) *http.Server {
server := &http.Server{
Addr: listenAddress,
ReadTimeout: constant.HTTPTimeout,
WriteTimeout: constant.HTTPTimeout,
}
return server
}
// Server Start HTTP server
func (config ServerConfig) Server() {
log.Println("Listening on " + config.HTTPServer.Addr)
http.HandleFunc("/", config.router)
log.Fatal(config.HTTPServer.ListenAndServe())
}

View file

@ -1,17 +0,0 @@
package utils
type ParseIntBeforeSeparatorError struct {
Message string
}
func (m *ParseIntBeforeSeparatorError) Error() string {
return "parseIntBeforeSeparator: " + m.Message
}
type ParseExpirationError struct {
Message string
}
func (m *ParseExpirationError) Error() string {
return "parseIntBeforeSeparator: " + m.Message
}

View file

@ -1,10 +0,0 @@
package plak
type DeletePlakError struct {
Name string
Err error
}
func (m *DeletePlakError) Error() string {
return "Cannot delete: " + m.Name + " : " + m.Err.Error()
}

View file

@ -1,134 +0,0 @@
package plak
import (
"context"
"io"
"log"
"net/http"
"time"
"git.gnous.eu/gnouseu/plakken/internal/database"
"git.gnous.eu/gnouseu/plakken/internal/utils"
"github.com/redis/go-redis/v9"
"html/template"
)
var ctx = context.Background()
type WebConfig struct {
DB *redis.Client
UrlLength uint8
}
// Plak "Object" for plak
type Plak struct {
Key string
Content string
Expiration time.Duration
DB *redis.Client
}
// Create manage POST request for create Plak
func (config WebConfig) Create(w http.ResponseWriter, r *http.Request) {
content := r.FormValue("content")
if content == "" {
w.WriteHeader(http.StatusBadRequest)
}
dbConf := database.DBConfig{
DB: config.DB,
}
secret := utils.GenerateSecret()
key := utils.GenerateUrl(config.UrlLength)
rawExpiration := r.FormValue("exp")
expiration, err := utils.ParseExpiration(rawExpiration)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
} else if expiration == 0 {
dbConf.InsertPaste(key, content, secret, -1)
} else {
dbConf.InsertPaste(key, content, secret, time.Duration(expiration*int(time.Second)))
}
http.Redirect(w, r, key, http.StatusSeeOther)
}
// View for plak
func (config WebConfig) View(w http.ResponseWriter, r *http.Request) {
dbConf := database.DBConfig{
DB: config.DB,
}
var plak Plak
key := r.PathValue("key")
if dbConf.UrlExist(key) {
plak = Plak{
Key: key,
DB: config.DB,
}
plak = plak.GetContent()
if r.PathValue("settings") == "raw" {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
_, err := io.WriteString(w, plak.Content)
if err != nil {
log.Println(err)
}
} else {
t, err := template.ParseFiles("templates/paste.html")
if err != nil {
log.Println(err)
}
err = t.Execute(w, plak)
if err != nil {
log.Println(err)
}
}
} else {
w.WriteHeader(http.StatusNotFound)
}
}
// Delete manage plak deletion endpoint
func (config WebConfig) Delete(w http.ResponseWriter, r *http.Request) {
dbConf := database.DBConfig{
DB: config.DB,
}
key := r.PathValue("key")
if dbConf.UrlExist(key) {
secret := r.URL.Query().Get("secret")
if dbConf.VerifySecret(key, secret) {
plak := Plak{
Key: key,
DB: config.DB,
}
err := plak.deletePlak()
if err != nil {
log.Println(err)
}
w.WriteHeader(http.StatusNoContent)
} else {
w.WriteHeader(http.StatusForbidden)
}
}
w.WriteHeader(http.StatusNotFound)
}
// deletePlak Delete plak from database
func (plak Plak) deletePlak() error {
err := plak.DB.Del(ctx, plak.Key).Err()
if err != nil {
log.Println(err)
return &DeletePlakError{Name: plak.Key, Err: err}
}
return nil
}
// GetContent get plak content
func (plak Plak) GetContent() Plak {
plak.Content = plak.DB.HGet(ctx, plak.Key, "content").Val()
return plak
}

View file

@ -1,15 +0,0 @@
package static
import (
"net/http"
)
// ServeStatic Serve static file from static
func ServeStatic(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "./static/"+r.PathValue("file")) // TODO: vérifier si c'est safe
}
// Home Serve index.html
func Home(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "./static/index.html")
}

112
main.go
View file

@ -1,21 +1,111 @@
package main package main
import ( import (
"git.gnous.eu/gnouseu/plakken/internal/config" "fmt"
"git.gnous.eu/gnouseu/plakken/internal/database" "github.com/redis/go-redis/v9"
"git.gnous.eu/gnouseu/plakken/internal/httpServer" "html/template"
"io"
"log"
"net/http"
"strings"
"time"
) )
var currentConfig Config
var db *redis.Client
type pasteView struct {
Content string
Key string
}
func handleRequest(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
clearPath := strings.ReplaceAll(r.URL.Path, "/raw", "")
staticResource := "/static/"
switch r.Method {
case "GET":
if path == "/" {
http.ServeFile(w, r, "./static/index.html")
} else if strings.HasPrefix(path, staticResource) {
fs := http.FileServer(http.Dir("./static"))
http.Handle(staticResource, http.StripPrefix(staticResource, fs))
} else {
if UrlExist(clearPath) {
if strings.HasSuffix(path, "/raw") {
pasteContent := getContent(clearPath)
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
_, err := io.WriteString(w, pasteContent)
if err != nil {
log.Println(err)
}
} else {
pasteContent := getContent(path)
s := pasteView{Content: pasteContent, Key: strings.TrimPrefix(path, "/")}
t, err := template.ParseFiles("templates/paste.html")
if err != nil {
log.Println(err)
}
err = t.Execute(w, s)
if err != nil {
log.Println(err)
}
}
} else {
w.WriteHeader(http.StatusNotFound)
}
}
case "POST":
if path == "/" {
secret := GenerateSecret()
url := "/" + GenerateUrl()
content := r.FormValue("content")
rawExpiration := r.FormValue("exp")
expiration, err := ParseExpiration(rawExpiration)
if err != nil {
log.Println(err)
} else if expiration == 0 {
insertPaste(url, content, secret, -1)
} else if expiration == -1 {
w.WriteHeader(http.StatusBadRequest)
} else {
insertPaste(url, content, secret, time.Duration(expiration*int(time.Second)))
}
http.Redirect(w, r, url, http.StatusSeeOther)
} else {
w.WriteHeader(http.StatusMethodNotAllowed)
}
case "DELETE":
if UrlExist(path) {
secret := r.URL.Query().Get("secret")
if VerifySecret(path, secret) {
DeleteContent(path)
w.WriteHeader(http.StatusNoContent)
} else {
w.WriteHeader(http.StatusForbidden)
}
} else {
w.WriteHeader(http.StatusNotFound)
}
}
}
func main() { func main() {
initConfig := config.GetConfig() db = ConnectDB()
dbConfig := database.InitDB(initConfig.RedisAddress, initConfig.RedisUser, initConfig.RedisPassword, initConfig.RedisDB) currentConfig = GetConfig()
db := database.ConnectDB(dbConfig) listen := currentConfig.host + ":" + currentConfig.port
http.HandleFunc("/", handleRequest)
serverConfig := httpServer.ServerConfig{ if currentConfig.host == "" {
HTTPServer: httpServer.Config(initConfig.ListenAddress), fmt.Println("Listening on port " + listen)
UrlLength: initConfig.UrlLength, } else {
DB: db, fmt.Println("Listening on " + listen)
} }
serverConfig.Server() err := http.ListenAndServe(listen, nil)
if err != nil {
log.Fatal(err)
}
} }

View file

@ -7,8 +7,9 @@
name="description"> name="description">
<meta content="Plakken" name="author"> <meta content="Plakken" name="author">
<meta content="width=device-width, initial-scale=1.0" name="viewport"> <meta content="width=device-width, initial-scale=1.0" name="viewport">
<title>New plak • Plakken</title><script async src="/static/app.js"></script> <title>New plak • Plakken</title>
<link href="/static/style.css" rel="stylesheet"> <link href="/static/style.css" rel="stylesheet">
<script async src="/static/app.js"></script>
</head> </head>
<body> <body>
<form method="post"> <form method="post">
@ -18,22 +19,19 @@
</div> </div>
<div> <div>
<label for="content"></label> <label for="content"></label>
<textarea autofocus id="content" name="content" placeholder="Type your paste here"></textarea> <textarea autofocus id="content" name="content" placeholder="Your paste here"></textarea>
<nav> <nav>
<ul> <ul>
<li> <li>
<label for="password"> <label for="password">Password?</label>
<input id="password" placeholder="Password" type="text"> <input id="password" type="text">
</label>
</li> </li>
<li><label for="exp">Expiration?</label>
<input id="exp" name="exp" type="text" placeholder="vide, 0 ou 1d1h1m1s"></li>
<li> <li>
<label for="exp"> <label for="type">Type</label>
<input id="exp" name="exp" placeholder="Expiration (1d1h1m1s)" type="text">
</label>
</li>
<li>
<label for="type">
<select id="type" name="type"> <select id="type" name="type">
<option value="auto">Auto Detect</option>
<option value="c">C</option> <option value="c">C</option>
<option value="cpp">C++</option> <option value="cpp">C++</option>
<option value="csharp">C#</option> <option value="csharp">C#</option>
@ -52,12 +50,12 @@
<option value="xml">XML</option> <option value="xml">XML</option>
<option value="yml">YAML</option> <option value="yml">YAML</option>
</select> </select>
</label>
</li> </li>
</ul> </ul>
<button title="Save plak" type="submit"> <button title="Save plak" type="submit">
<svg viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"> <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path d="M12.736 3.97a.733.733 0 0 1 1.047 0c.286.289.29.756.01 1.05L7.88 12.01a.733.733 0 0 1-1.065.02L3.217 8.384a.757.757 0 0 1 0-1.06.733.733 0 0 1 1.047 0l3.052 3.093 5.4-6.425z"></path> <polyline points="9 11 12 14 22 4"></polyline>
<path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"></path>
</svg> </svg>
</button> </button>
</nav> </nav>

View file

@ -1,9 +1,8 @@
:root { :root {
--accent: #be0560; --accent: #be0560;
--background: #121212; --background: #141414;
--border: #333; --border: #333;
--text: #e6e6e6; --text: #e9e9e9;
--placeholder: #666;
} }
body { body {
@ -18,32 +17,6 @@ form {
flex-flow: row wrap; flex-flow: row wrap;
} }
#lines {
color: var(--placeholder);
font: 400 14px/1.6 "JetBrains Mono", monospace;
height: calc(100vh - 29px);
overflow-y: hidden;
padding: 8px 0;
text-align: center;
user-select: none;
width: 26px;
}
input, select {
background-color: var(--background);
border: 2px solid var(--border);
border-radius: 2px;
color: var(--text);
font-size: 13px;
outline: none;
padding: 6px 8px;
transition: border .15s ease;
}
input:hover, select:hover {
border-color: var(--text);
}
button, textarea { button, textarea {
background-color: inherit; background-color: inherit;
border: none; border: none;
@ -51,20 +24,36 @@ button, textarea {
resize: none; resize: none;
} }
#lines {
color: #999;
font: 400 14px/1.6 "JetBrains Mono", monospace;
height: calc(100vh - 3rem);
overflow-y: hidden;
padding: 10px 0;
text-align: center;
user-select: none;
width: 26px;
}
#content { #content {
color: var(--text); color: var(--text);
font: 400 14px/1.6 "JetBrains Mono", monospace; font: 400 14px/1.6 "JetBrains Mono", monospace;
height: calc(100vh - 29px); height: calc(100vh - 3rem);
padding: 8px; padding: 10px 10px 10px 6px;
width: calc(100vw - 45px); width: calc(100vw - 42px);
}
pre {
margin: 15px;
} }
nav { nav {
top: 1rem; align-items: end;
bottom: 1rem;
display: flex; display: flex;
flex-flow: row wrap; flex-flow: row wrap;
position: absolute; position: absolute;
right: 12px; right: 1rem;
} }
ul { ul {
@ -76,12 +65,33 @@ ul {
padding: 0 1.9rem; padding: 0 1.9rem;
} }
label {
display: block;
}
input, select {
background-color: var(--background);
border: 2px solid var(--border);
border-radius: 2px;
color: var(--text);
font-size: 15px;
outline: none;
padding: 6px 8px;
transition: border .15s ease;
}
input:hover, select:hover {
border-color: var(--text);
}
svg { svg {
cursor: pointer; fill: none;
height: 24px; height: 26px;
fill: var(--text); stroke: var(--text);
stroke-width: 2;
stroke-linecap: round;
transition: .15s ease; transition: .15s ease;
width: 24px; width: 26px;
} }
svg:hover { svg:hover {
@ -92,6 +102,10 @@ input:focus-visible, select:focus-visible {
border: 2px solid var(--text); border: 2px solid var(--text);
} }
button:focus-visible {
outline: none;
}
::selection { ::selection {
background-color: var(--accent); background-color: var(--accent);
color: #fff; color: #fff;

View file

@ -1,81 +0,0 @@
package utils_test
import (
"errors"
"testing"
"git.gnous.eu/gnouseu/plakken/internal/utils"
)
func TestCheckCharNotRedundantTrue(t *testing.T) { // Test CheckCharRedundant with redundant char
want := true
got := utils.CheckCharRedundant("2d1h3md4h7s", "h")
if got != want {
t.Fatal("Error in parseExpirationFull, want : ", want, "got : ", got)
}
}
func TestCheckCharNotRedundantFalse(t *testing.T) { // Test CheckCharRedundant with not redundant char
want := false
got := utils.CheckCharRedundant("2d1h3m47s", "h")
if got != want {
t.Fatal("Error in parseExpirationFull, want : ", want, "got : ", got)
}
}
func TestParseExpirationFull(t *testing.T) { // test parseExpirationFull with all valid separator
result, _ := utils.ParseExpiration("2d1h3m47s")
correctValue := 176627
if result != correctValue {
t.Fatal("Error in parseExpirationFull, want : ", correctValue, "got : ", result)
}
}
func TestParseExpirationMissing(t *testing.T) { // test parseExpirationFull with all valid separator
result, _ := utils.ParseExpiration("1h47s")
correctValue := 3647
if result != correctValue {
t.Fatal("Error in ParseExpirationFull, want : ", correctValue, "got : ", result)
}
}
func TestParseExpirationWithCaps(t *testing.T) { // test parseExpirationFull with all valid separator
result, _ := utils.ParseExpiration("2D1h3M47s")
correctValue := 176627
if result != correctValue {
t.Fatal("Error in parseExpirationFull, want : ", correctValue, "got : ", result)
}
}
func TestParseExpirationNull(t *testing.T) { // test ParseExpirationFull with all valid separator
result, _ := utils.ParseExpiration("0")
correctValue := 0
if result != correctValue {
t.Fatal("Error in ParseExpirationFull, want: ", correctValue, "got: ", result)
}
}
func TestParseExpirationNegative(t *testing.T) { // test ParseExpirationFull with all valid separator
_, got := utils.ParseExpiration("-42h1m4s")
want := &utils.ParseExpirationError{}
if !errors.As(got, &want) {
t.Fatal("Error in ParseExpirationFull, want : ", want, "got : ", got)
}
}
func TestParseExpirationInvalid(t *testing.T) { // test ParseExpirationFull with all valid separator
_, got := utils.ParseExpiration("8h42h1m1d4s")
want := &utils.ParseExpirationError{}
if !errors.As(got, &want) {
t.Fatal("Error in ParseExpirationFull, want : ", want, "got : ", got)
}
}
func TestParseExpirationInvalidRedundant(t *testing.T) { // test ParseExpirationFull with all valid separator
_, got := utils.ParseExpiration("8h42h1m1h4s")
want := &utils.ParseExpirationError{}
if !errors.As(got, &want) {
t.Fatal("Error in ParseExpirationFull, want : ", want, "got : ", got)
}
}

View file

@ -1,18 +1,18 @@
package utils package main
import ( import (
"crypto/rand" "crypto/rand"
"encoding/hex" "encoding/hex"
"fmt"
"log" "log"
mathrand "math/rand" mathrand "math/rand"
"strconv" "strconv"
"strings" "strings"
) )
// GenerateUrl generate random string for plak url func GenerateUrl() string {
func GenerateUrl(length uint8) string {
listChars := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") listChars := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
b := make([]rune, length) b := make([]rune, currentConfig.urlLength)
for i := range b { for i := range b {
b[i] = listChars[mathrand.Intn(len(listChars))] b[i] = listChars[mathrand.Intn(len(listChars))]
} }
@ -20,7 +20,6 @@ func GenerateUrl(length uint8) string {
return string(b) return string(b)
} }
// GenerateSecret generate random secret (32 bytes hexadecimal)
func GenerateSecret() string { func GenerateSecret() string {
key := make([]byte, 32) key := make([]byte, 32)
_, err := rand.Read(key) _, err := rand.Read(key)
@ -31,73 +30,62 @@ func GenerateSecret() string {
return hex.EncodeToString(key) return hex.EncodeToString(key)
} }
// CheckCharRedundant verify is a character is redundant in a string func UrlExist(url string) bool {
func CheckCharRedundant(source string, char string) bool { // Verify if a char is redundant return db.Exists(ctx, url).Val() == 1
if strings.Count(source, char) > 1 {
return true
}
return false
} }
func parseIntBeforeSeparator(source *string, sep string) (int, error) { // return 0 & error if error, only accept positive number func VerifySecret(url string, secret string) bool {
if CheckCharRedundant(*source, sep) { return secret == db.HGet(ctx, url, "secret").Val()
return 0, &ParseIntBeforeSeparatorError{Message: *source + ": cannot parse value as int"}
} }
func parseIntBeforeSeparator(source *string, sep string) (int, error) { // return -1 if error, only accept positive number
var value int var value int
var err error var err error
if strings.Contains(*source, sep) { if strings.Contains(*source, sep) {
value, err = strconv.Atoi(strings.Split(*source, sep)[0]) value, err = strconv.Atoi(strings.Split(*source, sep)[0])
if err != nil { if err != nil {
log.Println(err) log.Println(err)
return 0, &ParseIntBeforeSeparatorError{Message: *source + ": cannot parse value as int"} return -1, fmt.Errorf("parseIntBeforeSeparator : \"%s\" : cannot parse value as int", *source)
} }
if value < 0 { // Only positive value is correct if value < 0 { // Only positive value is correct
return 0, &ParseIntBeforeSeparatorError{Message: *source + ": format only take positive value"} return -1, fmt.Errorf("parseIntBeforeSeparator : \"%s\" : format only take positive value", *source)
} }
if value > 99 {
return 0, &ParseIntBeforeSeparatorError{Message: *source + ": Format only take two number"}
}
*source = strings.Join(strings.Split(*source, sep)[1:], "") *source = strings.Join(strings.Split(*source, sep)[1:], "")
} }
return value, nil return value, nil
} }
// ParseExpiration Parse "1d1h1m1s" duration format. Return 0 & error if error func ParseExpiration(source string) (int, error) { // return -1 if error
func ParseExpiration(source string) (int, error) {
var expiration int var expiration int
var tempOutput int var tempOutput int
var err error var err error
errMessage := "ParseExpiration : \"%s\" : invalid syntax"
if source == "0" { if source == "0" {
return 0, nil return 0, nil
} }
source = strings.ToLower(source)
tempOutput, err = parseIntBeforeSeparator(&source, "d") tempOutput, err = parseIntBeforeSeparator(&source, "d")
expiration = tempOutput * 86400 expiration = tempOutput * 86400
if err != nil { if err != nil {
log.Println(err) log.Println(err)
return 0, &ParseExpirationError{Message: "Invalid syntax"} return -1, fmt.Errorf(errMessage, source)
} }
tempOutput, err = parseIntBeforeSeparator(&source, "h") tempOutput, err = parseIntBeforeSeparator(&source, "h")
expiration += tempOutput * 3600 expiration += tempOutput * 3600
if err != nil { if err != nil {
log.Println(err) log.Println(err)
return 0, &ParseExpirationError{Message: "Invalid syntax"} return -1, fmt.Errorf(errMessage, source)
} }
tempOutput, err = parseIntBeforeSeparator(&source, "m") tempOutput, err = parseIntBeforeSeparator(&source, "m")
expiration += tempOutput * 60 expiration += tempOutput * 60
if err != nil { if err != nil {
log.Println(err) log.Println(err)
return 0, &ParseExpirationError{Message: "Invalid syntax"} return -1, fmt.Errorf(errMessage, source)
} }
tempOutput, err = parseIntBeforeSeparator(&source, "s") tempOutput, err = parseIntBeforeSeparator(&source, "s")
expiration += tempOutput * 1 expiration += tempOutput * 1
if err != nil { if err != nil {
log.Println(err) log.Println(err)
return 0, &ParseExpirationError{Message: "Invalid syntax"} return -1, fmt.Errorf(errMessage, source)
} }
return expiration, nil return expiration, nil

43
utils_test.go Normal file
View file

@ -0,0 +1,43 @@
package main
import "testing"
func TestParseExpirationFull(t *testing.T) { // test parseExpirationFull with all valid separator
result, _ := ParseExpiration("2d1h3m47s")
correctValue := 176627
if result != correctValue {
t.Fatal("Error in parseExpirationFull, want : ", correctValue, "got : ", result)
}
}
func TestParseExpirationMissing(t *testing.T) { // test parseExpirationFull with all valid separator
result, _ := ParseExpiration("1h47s")
correctValue := 3647
if result != correctValue {
t.Fatal("Error in ParseExpirationFull, want : ", correctValue, "got : ", result)
}
}
func TestParseExpirationNull(t *testing.T) { // test ParseExpirationFull with all valid separator
result, _ := ParseExpiration("0")
correctValue := 0
if result != correctValue {
t.Fatal("Error in ParseExpirationFull, want : ", correctValue, "got : ", result)
}
}
func TestParseExpirationNegative(t *testing.T) { // test ParseExpirationFull with all valid separator
result, _ := ParseExpiration("-42h1m4s")
correctValue := -1
if result != correctValue {
t.Fatal("Error in ParseExpirationFull, want : ", correctValue, "got : ", result)
}
}
func TestParseExpirationInvalid(t *testing.T) { // test ParseExpirationFull with all valid separator
result, _ := ParseExpiration("8h42h1m1d4s")
correctValue := -1
if result != correctValue {
t.Fatal("Error in ParseExpirationFull, want : ", correctValue, "got : ", result)
}
}