Compare commits

..

2 Commits

Author SHA1 Message Date
472d175093 modify default content type 2025-04-01 13:26:14 -05:00
d34ef94ad7 fix cookie defaults 2025-04-01 11:56:57 -05:00
2 changed files with 32 additions and 16 deletions

View File

@ -3,6 +3,7 @@ package http
import ( import (
"context" "context"
"encoding/json" "encoding/json"
"fmt" // Added for fmt.Fprintf
"net" "net"
"net/http" "net/http"
"time" "time"
@ -279,21 +280,37 @@ func writeResponse(w http.ResponseWriter, result any) {
result = httpResp.Body // Set result to body for processing below result = httpResp.Body // Set result to body for processing below
} }
switch res := result.(type) { // Check if it's a map (table) or array - return as JSON
case string: isJSON := false
// String result - default to plain text
setContentTypeIfMissing(w, contentTypePlain) switch result.(type) {
w.Write([]byte(res)) case map[string]any, []any, []float64, []string, []int:
default: isJSON = true
// All other types - convert to JSON }
if isJSON {
setContentTypeIfMissing(w, contentTypeJSON) setContentTypeIfMissing(w, contentTypeJSON)
data, err := json.Marshal(res) data, err := json.Marshal(result)
if err != nil { if err != nil {
logger.Error("Failed to marshal response: %v", err) logger.Error("Failed to marshal response: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError) http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return return
} }
w.Write(data) w.Write(data)
return
}
// All other types - convert to plain text
setContentTypeIfMissing(w, contentTypePlain)
switch r := result.(type) {
case string:
w.Write([]byte(r))
case []byte:
w.Write(r)
default:
// Convert any other type to string
fmt.Fprintf(w, "%v", r)
} }
} }

View File

@ -117,23 +117,22 @@ local cookie = {
if opts.expires then if opts.expires then
if type(opts.expires) == "number" then if type(opts.expires) == "number" then
if opts.expires > 0 then if opts.expires > 0 then
-- Add seconds to current time
cookie.max_age = opts.expires cookie.max_age = opts.expires
local now = os.time() local now = os.time()
cookie.expires = now + opts.expires cookie.expires = now + opts.expires
elseif opts.expires < 0 then elseif opts.expires < 0 then
-- Session cookie (default) cookie.expires = 1
else
-- Expire immediately
cookie.expires = 0
cookie.max_age = 0 cookie.max_age = 0
else
-- opts.expires == 0: Session cookie
-- Do nothing (omitting both expires and max-age creates a session cookie)
end end
end end
end end
-- Set flags (http_only defaults to true) -- Security flags
cookie.secure = opts.secure or false cookie.secure = (opts.secure ~= false)
cookie.http_only = (opts.http_only ~= false) -- Default to true unless explicitly set to false cookie.http_only = (opts.http_only ~= false)
-- Store in cookies table -- Store in cookies table
local n = #resp.cookies + 1 local n = #resp.cookies + 1