implement running options

This commit is contained in:
csehviktor
2025-08-01 22:01:43 +02:00
parent aed36d860d
commit a9e46f5fcf
3 changed files with 32 additions and 12 deletions

View File

@@ -1,6 +1,6 @@
run:
dev:
@go tool templ generate
@go run .
@go run . -addr=":3000" -max-size=32768
gen:
@go tool templ generate
@@ -8,5 +8,6 @@ gen:
test:
@go test -v ./...
build:
@go build -o bin/main main.go
run:
@go build .
@./pastebin -addr=0.0.0.0:8080 -max-size=32768

View File

@@ -11,17 +11,28 @@ import (
type HttpHandler struct {
store *store.MemoryStore
maxSize int64
}
func NewHandler(store *store.MemoryStore) *HttpHandler {
func NewHandler(store *store.MemoryStore, maxSize int64) *HttpHandler {
return &HttpHandler{
store: store,
store,
maxSize,
}
}
func (h *HttpHandler) HandleSet(w http.ResponseWriter, r *http.Request) {
// form body request looks like:
// content=...
// so +8 additional bytes must be included
r.Body = http.MaxBytesReader(w, r.Body, h.maxSize+8)
if err := r.ParseForm(); err != nil {
badRequest("invalid bin", err, w, r)
if strings.Contains(err.Error(), "request body too large") {
badRequest("content too large", nil, w, r)
} else {
badRequest("invalid form data", err, w, r)
}
return
}
@@ -31,6 +42,8 @@ func (h *HttpHandler) HandleSet(w http.ResponseWriter, r *http.Request) {
return
}
//fmt.Println(len(content))
id, err := generateId()
if err != nil {
internal("could not generate id", err, w, r)

14
main.go
View File

@@ -1,6 +1,7 @@
package main
import (
"flag"
"log/slog"
"net/http"
@@ -8,12 +9,17 @@ import (
"github.com/csehviktor/pastebin/store"
)
const addr = ":3000"
func main() {
addrPtr := flag.String("addr", ":3000", "port to listen on")
maxSizePtr := flag.Int("max-size", 32*1024, "maximum size of a paste in bytes")
flag.Parse()
addr := *addrPtr
maxSize := int64(*maxSizePtr)
mux := http.NewServeMux()
store := store.NewMemoryStore()
httpHandler := handler.NewHandler(store)
httpHandler := handler.NewHandler(store, maxSize)
mux.HandleFunc("GET /style.css", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "view/style.css")
@@ -23,7 +29,7 @@ func main() {
mux.HandleFunc("GET /{id}", httpHandler.HandleGet)
mux.HandleFunc("GET /{id}/{theme}", httpHandler.HandleGet)
slog.Info("starting http server on", "addr", addr)
slog.Info("starting http server", "addr", addr, "maxSize", maxSize)
err := http.ListenAndServe(addr, mux)
if err != nil {
panic(err)