maint: changes

This commit is contained in:
vxclutch
2026-06-02 07:52:52 -04:00
parent 9ced6600e3
commit ec19585e9b
12 changed files with 147 additions and 61 deletions

View File

@@ -5,7 +5,7 @@ GO?= go
all: build all: build
build: build:
$(GO) build -o lash ./cmd/lash/ $(GO) build -o lash ./bin/main.go
lint: lint:
$(GO) fmt ./... $(GO) fmt ./...

2
TODO
View File

@@ -1,6 +1,4 @@
maint: clean up source code
maint: document more maint: document more
maint: make the colors more cross platform
feat: improve flags feat: improve flags
feat: replace uuid dep with custom id generator feat: replace uuid dep with custom id generator
feat: multiple files feat: multiple files

View File

@@ -35,7 +35,6 @@ func main() {
Handler: srv, Handler: srv,
} }
// TODO(vxc): Make this more portable
errx.Log("Your share link is %s", share.GenerateShareLink(*port)) errx.Log("Your share link is %s", share.GenerateShareLink(*port))
errx.Log("Your token is \033[1;92m%s\033[0m", lash.Token) errx.Log("Your token is \033[1;92m%s\033[0m", lash.Token)
errx.Log("starting server at http://0.0.0.0:%d", *port) errx.Log("starting server at http://0.0.0.0:%d", *port)

View File

@@ -1,19 +0,0 @@
package app
import (
"errors"
"flag"
"strings"
)
func GetFilePath() (string, error) {
fp := ""
for _, v := range flag.Args() {
if !strings.HasPrefix(v, "-") {
fp = v
return fp, nil
}
}
return "", errors.New("not enough arguments")
}

View File

@@ -1,6 +1,7 @@
package app package app
import ( import (
"flag"
"lash" "lash"
"lash/internal/errx" "lash/internal/errx"
"lash/internal/handlers" "lash/internal/handlers"
@@ -11,26 +12,29 @@ import (
func New(ctx *lash.LashContext) http.Handler { func New(ctx *lash.LashContext) http.Handler {
mux := http.NewServeMux() mux := http.NewServeMux()
fp, err := GetFilePath()
if err != nil {
errx.FatalPerror(err)
}
contents, err := os.ReadFile(fp)
if err != nil {
errx.FatalPerror(err)
}
share := handlers.ShareData{ share := handlers.ShareData{
Version: lash.Version, Version: lash.Version,
} }
file := handlers.FileHandler{ file := handlers.FileHandler{
Ctx: ctx, Ctx: ctx,
FileData: handlers.FileData{ }
fps := flag.Args()
if len(fps) < 1 {
errx.FatalPerror(errx.ErrNotEnoughArgs)
}
for _, fp := range fps {
contents, err := os.ReadFile(fp)
if err != nil {
errx.FatalPerror(err)
}
file.FileData = append(file.FileData, handlers.FileData{
Contents: contents, Contents: contents,
FileName: fp, FileName: fp,
}, })
} }
mux.HandleFunc("/", share.Handler) mux.HandleFunc("/", share.Handler)

5
internal/errx/define.go Normal file
View File

@@ -0,0 +1,5 @@
package errx
import "errors"
var ErrNotEnoughArgs error = errors.New("not enough arguments")

View File

@@ -0,0 +1,51 @@
package generator
import (
"math/rand/v2"
)
var keys []string = []string{
"octo",
"cool",
"whip",
"keys",
"cats",
"part",
"rate",
"face",
"lard",
"larp",
"dogs",
"cash",
"city",
"cold",
"desk",
"down",
"dirt",
"long",
"mean",
"news",
"only",
"open",
"year",
"wood",
"wing",
"work",
"wash",
"vote",
"onyx",
}
func Generate(n int) (code string) {
codeLen := n
start := rand.IntN(len(keys))
for i := range codeLen {
code += keys[(start+i)%len(keys)]
if i != codeLen-1 {
code += "-"
}
}
return
}

View File

@@ -1,9 +1,11 @@
package handlers package handlers
import ( import (
"archive/zip"
"encoding/json" "encoding/json"
"fmt" "fmt"
"lash" "lash"
"lash/internal/errx"
"net/http" "net/http"
"os" "os"
"strconv" "strconv"
@@ -11,7 +13,7 @@ import (
type FileHandler struct { type FileHandler struct {
Ctx *lash.LashContext Ctx *lash.LashContext
FileData FileData FileData []FileData
} }
type FileData struct { type FileData struct {
@@ -23,10 +25,17 @@ type ValidateRequest struct {
Token string Token string
} }
type headers map[string]string
var zipHeaders headers = headers{
"Content-Disposition": "attachment; filename=lash.zip",
"Content-Type": "application/octet-stream",
}
var sent int = 0 var sent int = 0
func (h FileHandler) APIHandler(w http.ResponseWriter, r *http.Request) { func (h FileHandler) APIHandler(w http.ResponseWriter, r *http.Request) {
if sent >= h.Ctx.N && h.Ctx.N != -1 { if h.hasHitMax() {
w.WriteHeader(http.StatusTooManyRequests) w.WriteHeader(http.StatusTooManyRequests)
os.Exit(0) os.Exit(0)
return return
@@ -45,27 +54,71 @@ func (h FileHandler) APIHandler(w http.ResponseWriter, r *http.Request) {
return return
} }
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", h.FileData.FileName))
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Length", strconv.Itoa(len(h.FileData.Contents)))
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
w.Write(h.FileData.Contents) if len(h.FileData) == 1 {
headers := headers{
"Content-Disposition": fmt.Sprintf("attachment; filename=%s", h.FileData[0].FileName),
"Content-Type": "application/octet-stream",
"Content-Length": strconv.Itoa(len(h.FileData[0].FileName)),
}
headers.set(w)
w.Write(h.FileData[0].Contents)
} else {
zipHeaders.set(w)
h.writeZip(w)
}
sent++ sent++
} }
func (h FileHandler) FileHandler(w http.ResponseWriter, r *http.Request) { func (h FileHandler) FileHandler(w http.ResponseWriter, r *http.Request) {
if sent >= h.Ctx.N && h.Ctx.N != -1 { if h.hasHitMax() {
w.WriteHeader(http.StatusTooManyRequests) w.WriteHeader(http.StatusTooManyRequests)
os.Exit(0) os.Exit(0)
return return
} }
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", h.FileData.FileName))
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Length", strconv.Itoa(len(h.FileData.Contents)))
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
w.Write(h.FileData.Contents) if len(h.FileData) == 1 {
headers := headers{
"Content-Disposition": fmt.Sprintf("attachment; filename=%s", h.FileData[0].FileName),
"Content-Type": "application/octet-stream",
"Content-Length": strconv.Itoa(len(h.FileData[0].FileName)),
}
headers.set(w)
w.Write(h.FileData[0].Contents)
} else {
zipHeaders.set(w)
h.writeZip(w)
}
sent++ sent++
} }
func (h FileHandler) writeZip(hw http.ResponseWriter) {
zw := zip.NewWriter(hw)
defer zw.Close()
for _, f := range h.FileData {
w, err := zw.Create(f.FileName)
if err != nil {
errx.FatalPerror(err)
}
_, err = w.Write(f.Contents)
if err != nil {
errx.FatalPerror(err)
}
}
}
func (h headers) set(w http.ResponseWriter) {
for k, v := range h {
w.Header().Set(k, v)
}
}
func (h FileHandler) hasHitMax() bool {
return sent >= h.Ctx.N && h.Ctx.N != -1
}

View File

@@ -13,7 +13,6 @@ type ShareData struct {
} }
func (h *ShareData) Handler(w http.ResponseWriter, r *http.Request) { func (h *ShareData) Handler(w http.ResponseWriter, r *http.Request) {
// Although `Must` can fail since `Templates` is embeded these files will always exist.
tmpl := template.Must(template.ParseFS(lash.Templates, "templates/share.html")) tmpl := template.Must(template.ParseFS(lash.Templates, "templates/share.html"))
if err := tmpl.ExecuteTemplate(w, "share.html", h); err != nil { if err := tmpl.ExecuteTemplate(w, "share.html", h); err != nil {

View File

@@ -2,9 +2,8 @@ package lash
import ( import (
"embed" "embed"
"lash/internal/generator"
"net/http" "net/http"
"github.com/google/uuid"
) )
type LashContext struct { type LashContext struct {
@@ -18,7 +17,6 @@ var Templates embed.FS
//go:embed version //go:embed version
var Version string var Version string
// TODO(vxc): Replace this with custom token generator var Token string = generator.Generate(5)
var Token string = uuid.New().String()
var ShareLinkToken string = uuid.New().String() var ShareLinkToken string = generator.Generate(8)

View File

@@ -24,11 +24,10 @@
<script> <script>
const tokenInput = document.getElementById('tokenInput'); const tokenInput = document.getElementById('tokenInput');
const submitBtn = document.getElementById('submitBtn'); const submitBtn = document.getElementById('submitBtn');
const status = document.getElementById('status');
const status = document.getElementById('status');
submitBtn.addEventListener('click', async () => { submitBtn.addEventListener('click', async () => {
const token = tokenInput.value.trim(); const token = tokenInput.value.trim();
if (!token) { if (!token) {
status.textContent = 'Please enter a token.'; status.textContent = 'Please enter a token.';
return; return;
@@ -42,7 +41,6 @@
}, },
body: JSON.stringify({ token }) body: JSON.stringify({ token })
}); });
if (!response.ok) { if (!response.ok) {
status.textContent = 'Download failed.'; status.textContent = 'Download failed.';
return; return;
@@ -50,19 +48,19 @@
const blob = await response.blob(); const blob = await response.blob();
const url = window.URL.createObjectURL(blob); const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url; a.href = url;
const a = document.createElement('a');
const disposition = response.headers.get('Content-Disposition'); const disposition = response.headers.get('Content-Disposition');
let filename = 'download.bin'; let filename = 'download.bin';
if (disposition && disposition.includes('filename=')) { if (disposition && disposition.includes('filename=')) {
filename = disposition filename = disposition
.split('filename=')[1] .split('filename=')[1]
.replace(/"/g, ''); .replace(/"/g, '');
} }
a.download = filename; a.download = filename;
document.body.appendChild(a); document.body.appendChild(a);
a.click(); a.click();
a.remove(); a.remove();

View File

@@ -1 +1 @@
3 6