diff --git a/src/client.c b/src/client.c index 3c5be03..94169c7 100755 --- a/src/client.c +++ b/src/client.c @@ -62,6 +62,23 @@ static inline void client_header_end(struct uh_client *cl) cl->printf(cl, "\r\n"); } +static inline void client_redirect(struct uh_client *cl, int code, const char *fmt, ...) +{ + va_list arg; + const char *summary = ((code == 301) ? "Moved Permanently" : "Found"); + + assert((code == 301 || code == 302) && fmt); + + cl->send_header(cl, code, summary, 0); + cl->printf(cl, "Location: "); + va_start(arg, fmt); + cl->vprintf(cl, fmt, arg); + va_end(arg); + + cl->printf(cl, "\r\n\r\n"); + cl->request_done(cl); +} + static void client_send_error(struct uh_client *cl, int code, const char *summary, const char *fmt, ...) { va_list arg; @@ -479,6 +496,7 @@ void uh_accept_client(struct uh_server *srv, bool ssl) cl->send_header = client_send_header; cl->append_header = client_append_header; cl->header_end = client_header_end; + cl->redirect = client_redirect; cl->request_done = client_request_done; cl->send = client_send; diff --git a/src/client.h b/src/client.h index 152bade..6d3e2db 100755 --- a/src/client.h +++ b/src/client.h @@ -94,6 +94,7 @@ struct uh_client { void (*send_header)(struct uh_client *cl, int code, const char *summary, int length); void (*append_header)(struct uh_client *cl, const char *name, const char *value); void (*header_end)(struct uh_client *cl); + void (*redirect)(struct uh_client *cl, int code, const char *fmt, ...); void (*request_done)(struct uh_client *cl); void (*send)(struct uh_client *cl, const void *data, int len); diff --git a/src/common.h b/src/common.h index 4ab551b..a4b7936 100755 --- a/src/common.h +++ b/src/common.h @@ -25,6 +25,7 @@ #include #include #include +#include #include #include #include diff --git a/src/file.c b/src/file.c index 444ff89..b171f9e 100755 --- a/src/file.c +++ b/src/file.c @@ -227,10 +227,7 @@ struct path_info *uh_path_lookup(struct uh_client *cl, const char *url) is missing in the request url, redirect the client to the same url with trailing slash appended */ if (!slash) { - cl->send_header(cl, 302, "Found", 0); - cl->printf(cl, "Location: %s%s%s\r\n\r\n", &path_phys[docroot_len], - query ? "?" : "", query ? query : ""); - cl->request_done(cl); + cl->redirect(cl, 302, "%s%s%s", &path_phys[docroot_len], query ? "?" : "", query ? query : ""); p.redirected = 1; return &p; }