Skip to content

Commit 34b6681

Browse files
authored
Merge pull request #771 from glmfe/feat/add-http-redir
feat(websocket): Add websocket HTTP redirect
2 parents 1f7828f + ce1560a commit 34b6681

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

components/esp_websocket_client/esp_websocket_client.c

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,12 @@ static const char *TAG = "websocket_client";
6464
#define WS_OVER_TCP_SCHEME "ws"
6565
#define WS_OVER_TLS_SCHEME "wss"
6666
#define WS_HTTP_BASIC_AUTH "Basic "
67+
#define WS_HTTP_REDIRECT(code) ((code >= 300) && (code < 400))
68+
69+
#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 5, 0)
70+
// Features supported in 5.5.0
71+
#define WS_TRANSPORT_REDIRECT_HEADER_SUPPORT 1
72+
#endif
6773

6874
const static int STOPPED_BIT = BIT0;
6975
const static int CLOSE_FRAME_SENT_BIT = BIT1; // Indicates that a close frame was sent by the client
@@ -1072,6 +1078,29 @@ static void esp_websocket_client_task(void *pv)
10721078
esp_websocket_client_abort_connection(client, WEBSOCKET_ERROR_TYPE_TCP_TRANSPORT);
10731079
break;
10741080
}
1081+
#if WS_TRANSPORT_REDIRECT_HEADER_SUPPORT
1082+
else if (WS_HTTP_REDIRECT(result)) {
1083+
const char *redir = esp_transport_ws_get_redir_uri(client->transport);
1084+
if (redir) {
1085+
// Redirecting to a new URI
1086+
free(client->config->uri);
1087+
1088+
client->config->uri = strdup(redir);
1089+
client->config->port = 0;
1090+
1091+
esp_websocket_client_set_uri(client, client->config->uri);
1092+
1093+
if (client->config->port == 0) {
1094+
client->config->port = esp_transport_get_default_port(client->transport);
1095+
}
1096+
1097+
// Rerun the connection with the redir uri.
1098+
client->state = WEBSOCKET_STATE_INIT;
1099+
ESP_LOGI(TAG, "Redirecting to %s", client->config->uri);
1100+
break;
1101+
}
1102+
}
1103+
#endif
10751104
ESP_LOGD(TAG, "Transport connected to %s://%s:%d", client->config->scheme, client->config->host, client->config->port);
10761105

10771106
client->state = WEBSOCKET_STATE_CONNECTED;

0 commit comments

Comments
 (0)