Implement basic POST request for curl #30

Closed
ada wants to merge 36 commits from ada/curl-upload into main
31 changed files with 963 additions and 381 deletions

7
.env
View file

@ -1,7 +1,6 @@
PLAKKEN_INTERFACE=0.0.0.0 PLAKKEN_LISTEN=:3000
PLAKKEN_PORT=3000 PLAKKEN_REDIS_ADDRESS=localhost:6379
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_REDIS_URL_LEN=5 PLAKKEN_URL_LENGTH=5

View file

@ -1,6 +0,0 @@
PLAKKEN_HOST=0.0.0.0
PLAKKEN_PORT=3000
PLAKKEN_REDIS_ADDR=localhost:6379
PLAKKEN_REDIS_USER=
PLAKKEN_REDIS_PASSWORD=
PLAKKEN_REDIS_DB=0

4
.gitignore vendored
View file

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

6
.idea/.gitignore vendored
View file

@ -1,6 +0,0 @@
# Default ignored files
/shelf/
/workspace.xml
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

View file

@ -1,8 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/plakken.iml" filepath="$PROJECT_DIR$/.idea/plakken.iml" />
</modules>
</component>
</project>

View file

@ -1,10 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="Go" enabled="true" />
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="highlight.js" level="application" />
</component>
</module>

View file

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

32
.woodpecker/build.yaml Normal file
View file

@ -0,0 +1,32 @@
steps:
- name: publish_image
image: woodpeckerci/plugin-docker-buildx
settings:
repo: git.gnous.eu/${CI_REPO_OWNER}/plakken
dockerfile: docker/Dockerfile
platforms: linux/amd64,linux/arm64/v8,linux/arm
registry: https://git.gnous.eu
tag: ${CI_COMMIT}
username:
from_secret: docker_username
password:
from_secret: docker_password
when:
branch: ${CI_REPO_DEFAULT_BRANCH}
event: push
- name: publish_image_tag
image: woodpeckerci/plugin-docker-buildx
settings:
repo: git.gnous.eu/${CI_REPO_OWNER}/plakken
dockerfile: docker/Dockerfile
platforms: linux/amd64,linux/arm64/v8,linux/arm
registry: https://git.gnous.eu
tags:
- ${CI_COMMIT_TAG##v} # Remove v from tag
- stable
username:
from_secret: docker_username
password:
from_secret: docker_password
when:
event: tag

24
.woodpecker/release.yaml Normal file
View file

@ -0,0 +1,24 @@
steps:
- name: Build
image: golang:1.22
commands:
- go mod download
- CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "-w -s" -o plakken-linux-amd64 # Enable static binary, target Linux, remove debug information and strip binary
- CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags "-w -s" -o plakken-linux-arm64
- CGO_ENABLED=0 GOOS=linux GOARCH=arm go build -ldflags "-w -s" -o plakken-linux-arm
- CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "-w -s" -o plakken-windows-amd64.exe
- CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags "-w -s" -o plakken-windows-arm64.exe
- CGO_ENABLED=0 GOOS=linux GOARCH=arm go build -ldflags "-w -s" -o plakken-windows-arm.exe
when:
event: tag
- name: Release
image: woodpeckerci/plugin-gitea-release
settings:
base_url: https://git.gnous.eu
files:
- "plakken*"
api_key:
from_secret: release_token
target: main
when:
event: tag

View file

@ -1,56 +0,0 @@
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")
}
conf := 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,
}
return conf
}

52
db.go
View file

@ -1,52 +0,0 @@
package main
import (
"context"
"github.com/redis/go-redis/v9"
"log"
"time"
)
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.Do(ctx, key, ttl)
}
}
func getContent(key string) string {
content := db.HGet(ctx, key, "content").Val()
return content
}
func deleteContent(key string) {
err := db.Del(ctx, key)
if err != nil {
log.Println(err)
}
}

28
docker/Dockerfile Normal file
View file

@ -0,0 +1,28 @@
# Build
FROM golang:1.22 AS build
LABEL authors="gnousEU"
WORKDIR /build
COPY go.mod go.sum ./
RUN go mod download
COPY main.go ./
COPY internal/ ./internal
COPY static/ ./static
COPY templates/ ./templates
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags "-w -s" # Enable static binary, target Linux, remove debug information and strip binary
# Copy to our image
FROM gcr.io/distroless/static-debian12:nonroot
WORKDIR /app
COPY --from=build /build/plakken ./
ENV PLAKKEN_LISTEN ":3000"
EXPOSE 3000/tcp
ENTRYPOINT ["/app/plakken"]

View file

@ -0,0 +1,31 @@
version: "3"
networks:
plakken:
external: false
services:
server:
build:
context: ../
dockerfile: docker/Dockerfile
restart: always
container_name: plakken
networks:
- plakken
ports:
- "3000:3000"
environment:
- PLAKKEN_REDIS_ADDRESS=redis:6379
- POSTGRES_PASSWORD=gitea
- PLAKKEN_REDIS_DB=0
- PLAKKEN_URL_LENGTH=5
depends_on:
- redis
redis:
image: redis:7-alpine
restart: always
healthcheck:
test: [ "CMD", "redis-cli", "ping" ]
networks:
- plakken

View file

@ -0,0 +1,36 @@
version: "3"
networks:
plakken:
external: false
volumes:
redis:
driver: local
services:
server:
image: git.gnous.eu/gnouseu/plakken:latest
restart: always
container_name: plakken
read_only: true
networks:
- plakken
ports:
- "3000:3000"
environment:
- PLAKKEN_REDIS_ADDRESS=redis:6379
- POSTGRES_PASSWORD=gitea
- PLAKKEN_REDIS_DB=0
- PLAKKEN_URL_LENGTH=5
depends_on:
- redis
redis:
image: redis:7-alpine
restart: always
healthcheck:
test: [ "CMD", "redis-cli", "ping" ]
networks:
- plakken
volumes:
- redis:/data

9
go.mod
View file

@ -1,11 +1,8 @@
module plakken module git.gnous.eu/gnouseu/plakken
go 1.21 go 1.22
require ( require github.com/redis/go-redis/v9 v9.5.0
github.com/joho/godotenv v1.5.1
github.com/redis/go-redis/v9 v9.2.1
)
require ( require (
github.com/cespare/xxhash/v2 v2.2.0 // indirect github.com/cespare/xxhash/v2 v2.2.0 // indirect

10
go.sum
View file

@ -1,8 +1,10 @@
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44= github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44=
github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= github.com/redis/go-redis/v9 v9.5.0 h1:Xe9TKMmZv939gwTBcvc0n1tzK5l2re0pKw/W/tN3amw=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= github.com/redis/go-redis/v9 v9.5.0/go.mod h1:hdY0cQFCN4fnSYT6TkisLufl/4W5UIXyv0b/CLO2V2M=
github.com/redis/go-redis/v9 v9.2.1 h1:WlYJg71ODF0dVspZZCpYmoF1+U1Jjk9Rwd7pq6QmlCg=
github.com/redis/go-redis/v9 v9.2.1/go.mod h1:hdY0cQFCN4fnSYT6TkisLufl/4W5UIXyv0b/CLO2V2M=

52
internal/config/config.go Normal file
View file

@ -0,0 +1,52 @@
package config
import (
"log"
"os"
"strconv"
)
// 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 {
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

@ -0,0 +1,8 @@
package constant
import "time"
const (
HTTPTimeout = 3 * time.Second
ExpirationCurlCreate = 604800 * time.Second // Second in one week
)

73
internal/database/db.go Normal file
View file

@ -0,0 +1,73 @@
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
}
// Ping test connection to Redis database
func Ping(db *redis.Client) error {
status := db.Ping(ctx)
if status.String() != "ping: PONG" {
return &PingError{}
}
return nil
}
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

@ -0,0 +1,7 @@
package database
type PingError struct{}
func (m *PingError) Error() string {
return "Connection to redis not work"
}

View file

@ -0,0 +1,67 @@
package httpServer
import (
"embed"
"log"
"net/http"
"git.gnous.eu/gnouseu/plakken/internal/constant"
"git.gnous.eu/gnouseu/plakken/internal/web/plak"
"github.com/redis/go-redis/v9"
)
type ServerConfig struct {
HTTPServer *http.Server
UrlLength uint8
DB *redis.Client
Static embed.FS
Templates embed.FS
}
func (config ServerConfig) home(w http.ResponseWriter, _ *http.Request) {
index, err := config.Static.ReadFile("static/index.html")
if err != nil {
log.Println(err)
}
_, err = w.Write(index)
if err != nil {
log.Println(err)
}
}
// Configure HTTP router
func (config ServerConfig) router() {
WebConfig := plak.WebConfig{
DB: config.DB,
UrlLength: config.UrlLength,
Templates: config.Templates,
}
staticFiles := http.FS(config.Static)
http.HandleFunc("GET /{$}", config.home)
http.Handle("GET /static/{file}", http.FileServer(staticFiles))
http.HandleFunc("GET /{key}/{settings...}", WebConfig.View)
http.HandleFunc("POST /{$}", WebConfig.CurlCreate)
http.HandleFunc("POST /create/{$}", 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)
config.router()
log.Fatal(config.HTTPServer.ListenAndServe())
}

17
internal/utils/error.go Normal file
View file

@ -0,0 +1,17 @@
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
}

112
internal/utils/utils.go Normal file
View file

@ -0,0 +1,112 @@
package utils
import (
"crypto/rand"
"encoding/hex"
"log"
mathrand "math/rand/v2"
"regexp"
"strconv"
"strings"
)
// GenerateUrl generate random string for plak url
func GenerateUrl(length uint8) string {
listChars := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
b := make([]rune, length)
for i := range b {
b[i] = listChars[mathrand.IntN(len(listChars))]
}
return string(b)
}
// GenerateSecret generate random secret (32 bytes hexadecimal)
func GenerateSecret() string {
key := make([]byte, 32)
_, err := rand.Read(key)
if err != nil {
log.Printf("Failed to generate secret")
}
return hex.EncodeToString(key)
}
// CheckCharRedundant verify is a character is redundant in a string
func CheckCharRedundant(source string, char string) bool { // Verify if a char is redundant
return strings.Count(source, char) > 1
}
func parseIntBeforeSeparator(source *string, sep string) (int, error) { // return 0 & error if error, only accept positive number
if CheckCharRedundant(*source, sep) {
return 0, &ParseIntBeforeSeparatorError{Message: *source + ": cannot parse value as int"}
}
var value int
var err error
if strings.Contains(*source, sep) {
value, err = strconv.Atoi(strings.Split(*source, sep)[0])
if err != nil {
log.Println(err)
return 0, &ParseIntBeforeSeparatorError{Message: *source + ": cannot parse value as int"}
}
if value < 0 { // Only positive value is correct
return 0, &ParseIntBeforeSeparatorError{Message: *source + ": format only take positive value"}
}
if value > 99 {
return 0, &ParseIntBeforeSeparatorError{Message: *source + ": Format only take two number"}
}
*source = strings.Join(strings.Split(*source, sep)[1:], "")
}
return value, nil
}
// ParseExpiration Parse "1d1h1m1s" duration format. Return 0 & error if error
func ParseExpiration(source string) (int, error) {
var expiration int
var tempOutput int
var err error
if source == "0" {
return 0, nil
}
source = strings.ToLower(source)
tempOutput, err = parseIntBeforeSeparator(&source, "d")
expiration = tempOutput * 86400
if err != nil {
log.Println(err)
return 0, &ParseExpirationError{Message: "Invalid syntax"}
}
tempOutput, err = parseIntBeforeSeparator(&source, "h")
expiration += tempOutput * 3600
if err != nil {
log.Println(err)
return 0, &ParseExpirationError{Message: "Invalid syntax"}
}
tempOutput, err = parseIntBeforeSeparator(&source, "m")
expiration += tempOutput * 60
if err != nil {
log.Println(err)
return 0, &ParseExpirationError{Message: "Invalid syntax"}
}
tempOutput, err = parseIntBeforeSeparator(&source, "s")
expiration += tempOutput * 1
if err != nil {
log.Println(err)
return 0, &ParseExpirationError{Message: "Invalid syntax"}
}
return expiration, nil
}
// ValidKey Verify if a key is valid (only letter, number, - and _)
func ValidKey(key string) bool {
result, err := regexp.MatchString("^[a-zA-Z0-9_.-]*$", key)
if err != nil {
return false
}
log.Println(key, result)
return result
}

View file

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

192
internal/web/plak/plak.go Normal file
View file

@ -0,0 +1,192 @@
package plak
import (
"context"
"embed"
"io"
"log"
"net/http"
"time"
"git.gnous.eu/gnouseu/plakken/internal/constant"
"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
Templates embed.FS
}
// 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)
return
}
dbConf := database.DBConfig{
DB: config.DB,
}
filename := r.FormValue("filename")
var key string
if len(filename) == 0 {
key = utils.GenerateUrl(config.UrlLength)
} else {
if !utils.ValidKey(filename) {
w.WriteHeader(http.StatusBadRequest)
return
}
if dbConf.UrlExist(filename) {
w.WriteHeader(http.StatusBadRequest)
return
}
key = filename
}
secret := utils.GenerateSecret()
rawExpiration := r.FormValue("exp")
expiration, err := utils.ParseExpiration(rawExpiration)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
} 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)
}
// CurlCreate Create plak with minimum param, ideal for curl. Force 7 day expiration
func (config WebConfig) CurlCreate(w http.ResponseWriter, r *http.Request) {
if r.ContentLength == 0 {
w.WriteHeader(http.StatusBadRequest)
return
}
content, _ := io.ReadAll(r.Body)
err := r.Body.Close()
if err != nil {
log.Println(err)
}
key := utils.GenerateUrl(config.UrlLength)
secret := utils.GenerateSecret()
dbConf := database.DBConfig{
DB: config.DB,
}
dbConf.InsertPaste(key, string(content), secret, constant.ExpirationCurlCreate)
var baseURL string
if r.TLS == nil {
baseURL = "http://" + r.Host + "/" + key
} else {
baseURL = "https://" + r.Host + "/" + key
}
message := baseURL + "\n" + "Delete with : 'curl -X DELETE " + baseURL + "?secret\\=" + secret + "'" + "\n"
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
_, err = io.WriteString(w, message)
if err != nil {
log.Println(err)
}
}
// 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.ParseFS(config.Templates, "templates/paste.html")
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
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)
return
} else {
w.WriteHeader(http.StatusForbidden)
return
}
}
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
}

116
main.go
View file

@ -1,103 +1,37 @@
package main package main
import ( import (
"fmt" "embed"
"github.com/redis/go-redis/v9"
"html/template"
"io"
"log" "log"
"net/http"
"strings" "git.gnous.eu/gnouseu/plakken/internal/config"
"git.gnous.eu/gnouseu/plakken/internal/database"
"git.gnous.eu/gnouseu/plakken/internal/httpServer"
) )
var currentConfig config var (
var db *redis.Client //go:embed templates
templates embed.FS
type pasteView struct { //go:embed static
Content string static embed.FS
Key string )
}
func handleRequest(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
clearPath := strings.ReplaceAll(r.URL.Path, "/raw", "")
switch r.Method {
case "GET":
if path == "/" {
http.ServeFile(w, r, "./static/index.html")
} else if strings.HasPrefix(path, "/static/") {
fs := http.FileServer(http.Dir("./static"))
http.Handle("/static/", http.StripPrefix("/static/", fs))
} else {
if urlExist(clearPath) {
if strings.HasSuffix(path, "/raw") {
pasteContent := getContent(clearPath)
w.Header().Set("Content-Type", "text/plain")
_, 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")
insertPaste(url, content, secret, -1)
http.Redirect(w, r, url, http.StatusSeeOther)
} else {
w.WriteHeader(http.StatusMethodNotAllowed)
}
case "DELETE":
if strings.HasPrefix(path, "/delete") {
urlItem := strings.Split(path, "/")
if urlExist("/" + urlItem[2]) {
secret := r.URL.Query().Get("secret")
if verifySecret("/"+urlItem[2], secret) {
deleteContent("/" + urlItem[2])
w.WriteHeader(http.StatusNoContent)
} else {
w.WriteHeader(http.StatusForbidden)
}
} else {
w.WriteHeader(http.StatusNotFound)
}
} else {
w.WriteHeader(http.StatusMethodNotAllowed)
}
}
}
func main() { func main() {
db = connectDB() initConfig := config.GetConfig()
currentConfig = getConfig() dbConfig := database.InitDB(initConfig.RedisAddress, initConfig.RedisUser, initConfig.RedisPassword, initConfig.RedisDB)
listen := currentConfig.host + ":" + currentConfig.port db := database.ConnectDB(dbConfig)
http.HandleFunc("/", handleRequest) err := database.Ping(db)
if currentConfig.host == "" {
fmt.Println("Listening on port " + listen)
} else {
fmt.Println("Listening on " + listen)
}
err := http.ListenAndServe(listen, nil)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
serverConfig := httpServer.ServerConfig{
HTTPServer: httpServer.Config(initConfig.ListenAddress),
UrlLength: initConfig.UrlLength,
DB: db,
Static: static,
Templates: templates,
}
serverConfig.Server()
} }

View file

@ -0,0 +1,31 @@
const codeEditor = document.getElementById('content');
const lineCounter = document.getElementById('lines');
let lineCountCache = 0;
// Update line counter
function updateLineCounter() {
const lineCount = codeEditor.value.split('\n').length;
if (lineCountCache !== lineCount) {
const outarr = Array.from({length: lineCount}, (_, index) => index + 1);
lineCounter.value = outarr.join('\n');
}
lineCountCache = lineCount;
}
codeEditor.addEventListener('input', updateLineCounter);
codeEditor.addEventListener('keydown', (e) => {
if (e.key === 'Tab') {
e.preventDefault();
const {value, selectionStart, selectionEnd} = codeEditor;
codeEditor.value = `${value.slice(0, selectionStart)}\t${value.slice(selectionEnd)}`;
codeEditor.setSelectionRange(selectionStart + 1, selectionStart + 1);
updateLineCounter();
}
});
updateLineCounter();

View file

@ -7,52 +7,61 @@
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> <title>New plak • Plakken</title><script async src="/static/app.js"></script>
<link href="/static/style.css" rel="stylesheet"> <link href="/static/style.css" rel="stylesheet">
</head> </head>
<body> <body>
<form method="post"> <form action="/create/" method="post">
<label for="content"></label> <div>
<textarea autofocus id="content" name="content" placeholder="Your paste here"></textarea> <label for="lines"></label>
<nav> <textarea id="lines" readonly wrap="hard">1</textarea>
<ul> </div>
<li> <div>
<label for="password">Password?</label> <label for="content"></label>
<input id="password" type="text"> <textarea autofocus id="content" name="content" placeholder="Type your paste here"></textarea>
</li> <nav>
<li><label for="exp">Expiration?</label> <ul>
<input id="exp" type="date"></li> <li>
<li> <label for="password">
<label for="type">Type</label> <input id="password" placeholder="Password" type="text">
<select id="type" name="type"> </label>
<option value="auto">Auto Detect</option> </li>
<option value="c">C</option> <li>
<option value="cpp">C++</option> <label for="exp">
<option value="csharp">C#</option> <input id="exp" name="exp" placeholder="Expiration (1d1h1m1s)" type="text">
<option value="css">CSS</option> </label>
<option value="go">Go</option> </li>
<option value="java">Java</option> <li>
<option value="js">Javascript</option> <label for="type">
<option value="html">HTML</option> <select id="type" name="type">
<option selected value="plain">Plaintext</option> <option value="c">C</option>
<option value="python">Python</option> <option value="cpp">C++</option>
<option value="rb">Ruby</option> <option value="csharp">C#</option>
<option value="rs">Rust</option> <option value="css">CSS</option>
<option value="sh">Shell</option> <option value="go">Go</option>
<option value="sql">SQL</option> <option value="java">Java</option>
<option value="ts">Typescript</option> <option value="js">Javascript</option>
<option value="xml">XML</option> <option value="html">HTML</option>
<option value="yml">YAML</option> <option selected value="plain">Plaintext</option>
</select> <option value="python">Python</option>
</li> <option value="rb">Ruby</option>
</ul> <option value="rs">Rust</option>
<button type="submit" title="Save plak"> <option value="sh">Shell</option>
<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"> <option value="sql">SQL</option>
<polyline points="9 11 12 14 22 4"></polyline> <option value="ts">Typescript</option>
<path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"></path> <option value="xml">XML</option>
</svg> <option value="yml">YAML</option>
</button> </select>
</nav> </label>
</li>
</ul>
<button title="Save plak" type="submit">
<svg viewBox="0 0 16 16" 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>
</svg>
</button>
</nav>
</div>
</form> </form>
</body> </body>
</html> </html>

View file

@ -1,8 +1,9 @@
:root { :root {
--accent: #be0560; --accent: #be0560;
--background: #141414; --background: #121212;
--border: #333; --border: #333;
--text: #e2e2e2; --text: #e6e6e6;
--placeholder: #666;
} }
body { body {
@ -12,45 +13,20 @@ body {
margin: 0; margin: 0;
} }
button, textarea { form {
background-color: inherit;
border: none;
}
textarea {
color: var(--text);
font: 14px/1.6 "JetBrains Mono", monospace;
height: calc(100vh - 3rem);
outline: none;
padding: 1rem;
resize: none;
width: calc(100vw - 2rem);
}
pre {
margin: 15px;
}
nav {
align-items: end;
bottom: 1rem;
display: flex; display: flex;
flex-flow: row wrap; flex-flow: row wrap;
position: absolute;
right: 1rem;
} }
ul { #lines {
display: flex; color: var(--placeholder);
flex-flow: row wrap; font: 400 14px/1.6 "JetBrains Mono", monospace;
gap: 2.6rem; height: calc(100vh - 29px);
list-style: none; overflow-y: hidden;
margin: 0; padding: 8px 0;
padding: 0 1.9rem; text-align: center;
} user-select: none;
width: 26px;
label {
display: block;
} }
input, select { input, select {
@ -58,9 +34,9 @@ input, select {
border: 2px solid var(--border); border: 2px solid var(--border);
border-radius: 2px; border-radius: 2px;
color: var(--text); color: var(--text);
font-size: 15px; font-size: 13px;
outline: none; outline: none;
padding: 5px 6px; padding: 6px 8px;
transition: border .15s ease; transition: border .15s ease;
} }
@ -68,14 +44,44 @@ input:hover, select:hover {
border-color: var(--text); border-color: var(--text);
} }
button, textarea {
background-color: inherit;
border: none;
outline: none;
resize: none;
}
#content {
color: var(--text);
font: 400 14px/1.6 "JetBrains Mono", monospace;
height: calc(100vh - 29px);
padding: 8px;
width: calc(100vw - 45px);
}
nav {
top: 1rem;
display: flex;
flex-flow: row wrap;
position: absolute;
right: 12px;
}
ul {
display: flex;
flex-flow: row wrap;
gap: 36px;
list-style: none;
margin: 0;
padding: 0 1.9rem;
}
svg { svg {
fill: none; cursor: pointer;
height: 26px; height: 24px;
stroke: var(--text); fill: var(--text);
stroke-width: 2;
stroke-linecap: round;
transition: .15s ease; transition: .15s ease;
width: 26px; width: 24px;
} }
svg:hover { svg:hover {
@ -86,10 +92,6 @@ 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;

99
test/utils/utils_test.go Normal file
View file

@ -0,0 +1,99 @@
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)
}
}
func TestValidKey(t *testing.T) { // test ValidKey with a valid key
got := utils.ValidKey("ab_a-C42")
want := true
if got != want {
t.Fatal("Error in ValidKey, want : ", want, "got : ", got)
}
}
func TestInValidKey(t *testing.T) { // test ValidKey with invalid key
got := utils.ValidKey("ab_?a-C42")
want := false
if got != want {
t.Fatal("Error in ValidKey, want : ", want, "got : ", got)
}
}

View file

@ -1,40 +0,0 @@
package main
import (
"crypto/rand"
"encoding/hex"
"log"
mathrand "math/rand"
)
func generateUrl() string {
listChars := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
b := make([]rune, currentConfig.urlLength)
for i := range b {
b[i] = listChars[mathrand.Intn(len(listChars))]
}
return string(b)
}
func generateSecret() string {
key := make([]byte, 32)
_, err := rand.Read(key)
if err != nil {
log.Printf("Failed to generate secret")
}
return hex.EncodeToString(key)
}
func urlExist(url string) bool {
exist := db.Exists(ctx, url).Val()
return exist == 1
}
func verifySecret(url string, secret string) bool {
if secret == db.HGet(ctx, url, "secret").Val() {
return true
}
return false
}