diff --git a/tool/net/help.txt b/tool/net/help.txt index 1e087b29f..19d897ab3 100644 --- a/tool/net/help.txt +++ b/tool/net/help.txt @@ -1001,13 +1001,18 @@ FUNCTIONS causes what would normally happen outside a dynamic handler to happen. The asset can be sourced from either the zip or local filesystem if -D is used. This function is mutually exclusive with - SetStatus and ServeError. + SetStatus and other Serve* functions. ServeError(code:int[,reason:str]) Instructs redbean to serve a boilerplate error page. This takes care of logging the error, setting the reason phrase, and adding a payload. This function is mutually exclusive with SetStatus and - ServeAsset. + other Serve* functions. + + ServeRedirect(code:int,location:str) + Instructs redbean to return the specified redirect code along with + the Location header set. This function is mutually exclusive with + SetStatus and other Serve* functions. SetLogLevel(level:int) Sets logger verbosity. Reasonable values for level are kLogDebug > diff --git a/tool/net/redbean.c b/tool/net/redbean.c index 371886586..eb3cbd68d 100644 --- a/tool/net/redbean.c +++ b/tool/net/redbean.c @@ -3059,6 +3059,32 @@ static int LuaServeIndex(lua_State *L) { return 1; } +static int LuaServeRedirect(lua_State *L) { + size_t loclen; + const char *location; + int code; + OnlyCallDuringRequest("ServeRedirect"); + + code = luaL_checkinteger(L, 1); + if (!(300 <= code && code <= 399)) { + luaL_argerror(L, 1, "bad status code for redirect"); + unreachable; + } + location = luaL_checklstring(L, 2, &loclen); + + if (msg.version < 10) { + (void)ServeError(505, "HTTP Version Not Supported"); + lua_pushboolean(L, false); + } else { + LOGF("REDIRECT %d to %s", code, location); + luaheaderp = AppendHeader( + SetStatus(code, GetHttpReason(code)), "Location", + FreeLater(EncodeHttpHeaderValue(location, loclen, 0))); + lua_pushboolean(L, true); + } + return 1; +} + static int LuaRoutePath(lua_State *L) { size_t pathlen; const char *path; @@ -5214,6 +5240,7 @@ static const luaL_Reg kLuaFuncs[] = { {"ServeError", LuaServeError}, // {"ServeIndex", LuaServeIndex}, // {"ServeListing", LuaServeListing}, // + {"ServeRedirect", LuaServeRedirect}, // {"ServeStatusz", LuaServeStatusz}, // {"SetHeader", LuaSetHeader}, // {"SetLogLevel", LuaSetLogLevel}, //