libhttp
libhttp copied to clipboard
How to perform as an HTTP client using libhttp?
Hi dear @lammertb ,
I'm trying to embed the libhttp in my own projects to act as both the server & client.
But actually, I encountered some challenges when trying to connect to an HTTPS server using libhttp.
- At first I only had an instance of
struct lh_ctx_tto set up the server, which I then passed tohttplib_connect_client. Everything went well, except that it crashed when I tried to callhttplib_stop(src/httplib_free_context.c:100). It was trying to clean up SSL_CTX, which was overwritten by another context when it acted as an HTTPS client. - Then I literally realized that I should call
httplib_create_client_contextto generate another instance ofstruct lh_ctx_tfor each client connection. But this time it crashes again inhttplib_close_connection(src/httplib_close_connection.c:124) because there is no place to initializeclient_ctx->workerthreadids. Also,client_ctxis always in theCTX_STATUS_TERMINATEDstatus after creation and cannot beCTX_STATUS_RUNNING, which prevents me from sending Hello to other servers.
Could you please give me some advice?
Thanks in advance.
Regards.
I have used this change to make a temporary solution, if there is anything else to add please let me know.
diff --git a/3rd_src/libhttp-1.8/src/httplib_close_connection.c b/3rd_src/libhttp-1.8/src/httplib_close_connection.c
index 2e84178..006ba5e 100644
--- a/3rd_src/libhttp-1.8/src/httplib_close_connection.c
+++ b/3rd_src/libhttp-1.8/src/httplib_close_connection.c
@@ -124,8 +124,7 @@ void httplib_close_connection( struct lh_ctx_t *ctx, struct lh_con_t *conn ) {
if ( client_ctx->workerthreadids[i] != 0 ) httplib_pthread_join( client_ctx->workerthreadids[i], NULL );
}
- client_ctx->workerthreadids = httplib_free( client_ctx->workerthreadids );
- client_ctx = httplib_free( client_ctx );
+ httplib_destroy_client_context(client_ctx);
httplib_pthread_mutex_destroy( & conn->mutex );
diff --git a/3rd_src/libhttp-1.8/src/httplib_connect_client.c b/3rd_src/libhttp-1.8/src/httplib_connect_client.c
index 1464ae9..c46ff96 100644
--- a/3rd_src/libhttp-1.8/src/httplib_connect_client.c
+++ b/3rd_src/libhttp-1.8/src/httplib_connect_client.c
@@ -40,7 +40,8 @@ static struct lh_con_t * httplib_connect_client_impl( struct lh_ctx_t *ctx, cons
*/
LIBHTTP_API struct lh_con_t *httplib_connect_client_secure( struct lh_ctx_t *ctx, const struct httplib_client_options *client_options ) {
-
+ ctx->status = CTX_STATUS_RUNNING;
+ ctx->num_threads = 0;
return httplib_connect_client_impl( ctx, client_options, true );
} /* httplib_connect_client_secure */
@@ -59,7 +60,8 @@ struct lh_con_t *httplib_connect_client( struct lh_ctx_t *ctx, const char *host,
memset( &opts, 0, sizeof(opts) );
opts.host = host;
opts.port = port;
-
+ ctx->status = CTX_STATUS_RUNNING;
+ ctx->num_threads = 0;
return httplib_connect_client_impl( ctx, &opts, use_ssl );
} /* httplib_connect_client */