### CMakeLists.txt for NATS.c Examples Source: https://github.com/nats-io/nats.c/blob/main/examples/getstarted/CMakeLists.txt This file configures the build process for the NATS.c examples using CMake. ```cmake if(NOT NATS_BUILD_EXAMPLES) return() endif() # We need this directory to build the examples include_directories(${PROJECT_SOURCE_DIR}/src) include_directories(${PROJECT_SOURCE_DIR}/examples/getstarted) # Get all the .c files in the examples directory file(GLOB EXAMPLES_SOURCES RELATIVE ${PROJECT_SOURCE_DIR}/examples/getstarted *.c) if(NOT NATS_BUILD_STATIC_EXAMPLES) add_definitions(-Dnats_IMPORTS) endif() if(NATS_BUILD_WITH_TLS) include_directories(${OPENSSL_INCLUDE_DIR}) endif(NATS_BUILD_WITH_TLS) # For each file... foreach(examples_src ${EXAMPLES_SOURCES}) # Remove the suffix so that it becomes the executable name string(REPLACE ".c" "" examplename ${examples_src}) set(exampleexe "${examplename}") # Build the executable add_executable(${exampleexe} ${PROJECT_SOURCE_DIR}/examples/getstarted/${examples_src}) # Link if(NATS_BUILD_STATIC_EXAMPLES) target_link_libraries(${exampleexe} nats_static ${NATS_EXTRA_LIB}) else() target_link_libraries(${exampleexe} nats ${NATS_EXTRA_LIB}) endif() endforeach() ``` -------------------------------- ### License Header Example Source: https://github.com/nats-io/nats.c/blob/main/CLAUDE.md Every file starts with the Apache 2.0 license header. ```c // Copyright 20XX The NATS Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. ``` -------------------------------- ### Installing libsodium on Linux Source: https://github.com/nats-io/nats.c/blob/main/README.md Install the libsodium library on Linux using apt-get. ```bash apt-get install libsodium-dev ``` -------------------------------- ### Object Store Configuration Example Source: https://github.com/nats-io/nats.c/blob/main/doc/html/structobj_store_config.html Example of initializing and configuring an objStoreConfig structure to create an object store. ```c objStore *obs = NULL; objStoreConfig cfg; objStoreConfig_Init(&cfg); cfg.Bucket = "TEST"; cfg.Description = "Testing ObjectStore"; cfg.Storage = js_MemoryStorage; cfg.TTL = 10000; // 10 seconds cfg.MaxBytes = 1024*1024*1024; cfg.Metadata.List = (const char*[]){"field1", "value1", "field2", "value2"}; cfg.Metadata.Count = 2; s = js_CreateObjectStore(&obs, js, &cfg); ``` -------------------------------- ### js_PurgeStream Example Source: https://github.com/nats-io/nats.c/blob/main/doc/html/group__js_assets_group.html Example demonstrating how to purge a stream with advanced options using jsOptions. ```c jsOptions o; jsOptions_Init(&o); o.Stream.Purge.Subject = "foo"; o.Stream.Purge.Sequence = 4; js_PurgeStream(js, "MY_STREAM", &o, &jerr); ``` -------------------------------- ### Static Library Installation Source: https://github.com/nats-io/nats.c/blob/main/src/CMakeLists.txt Installs the static NATS library, export configuration, and version information. ```cmake if(NATS_BUILD_LIB_STATIC) set_property(TARGET nats_static PROPERTY DEBUG_POSTFIX d) target_include_directories(nats_static PUBLIC $ $) install(TARGETS nats_static EXPORT cnats-targets ARCHIVE DESTINATION ${NATS_LIBDIR}) install(EXPORT cnats-targets NAMESPACE cnats:: FILE cnats-config.cmake DESTINATION ${NATS_LIBDIR}/cmake/cnats) install(FILES "${PROJECT_BINARY_DIR}/cnats-config-version.cmake" DESTINATION ${NATS_LIBDIR}/cmake/cnats) endif(NATS_BUILD_LIB_STATIC) ``` -------------------------------- ### NATS.c Examples CMakeLists.txt Source: https://github.com/nats-io/nats.c/blob/main/examples/CMakeLists.txt This is the main CMakeLists.txt file for the NATS.c examples project. It handles conditional compilation based on build flags and dynamically finds and builds example executables. ```cmake if(NOT NATS_BUILD_EXAMPLES) return() endif() if(NOT NATS_BUILD_STATIC_EXAMPLES AND NOT NATS_BUILD_LIB_SHARED) MESSAGE(FATAL_ERROR "Building examples require shared library, or run CMake with -DNATS_BUILD_STATIC_EXAMPLES=ON") endif() # We need this directory to build the examples include_directories(${PROJECT_SOURCE_DIR}/src) include_directories(${PROJECT_SOURCE_DIR}/examples) if(NATS_BUILD_LIBUV_EXAMPLE AND LIBUV_DIR) include_directories(${LIBUV_DIR}/include) endif() if(NATS_BUILD_LIBEVENT_EXAMPLE AND LIBEVENT_DIR) include_directories(${LIBEVENT_DIR}/include) endif() if(NATS_BUILD_WITH_TLS) include_directories(${OPENSSL_INCLUDE_DIR}) endif(NATS_BUILD_WITH_TLS) if(WIN32) set(LIB_SUFFIX ${CMAKE_STATIC_LIBRARY_SUFFIX}) else() if(NATS_BUILD_STATIC_EXAMPLES) set(LIB_SUFFIX ${CMAKE_STATIC_LIBRARY_SUFFIX}) else() set(LIB_SUFFIX ${CMAKE_SHARED_LIBRARY_SUFFIX}) endif() endif() # Get all the .c files in the examples directory file(GLOB EXAMPLES_SOURCES RELATIVE ${PROJECT_SOURCE_DIR}/examples *.c) if(NOT NATS_BUILD_STATIC_EXAMPLES) add_definitions(-Dnats_IMPORTS) endif() # For each file... foreach(examples_src ${EXAMPLES_SOURCES}) # Remove the suffix so that it becomes the executable name string(REPLACE ".c" "" examplename ${examples_src}) set(exampleexe "nats-${examplename}") set(buildExample OFF) set(NATS_ASYNC_IO_LIB "") if(examplename MATCHES "libuv") if(NATS_BUILD_LIBUV_EXAMPLE) set(buildExample ON) if(LIBUV_DIR) set(NATS_ASYNC_IO_LIB ${LIBUV_DIR}/lib/libuv${LIB_SUFFIX}) else() set(NATS_ASYNC_IO_LIB uv) endif() endif() elseif(examplename MATCHES "libevent") if(NATS_BUILD_LIBEVENT_EXAMPLE) set(buildExample ON) if(LIBEVENT_DIR) if(WIN32) set(NATS_ASYNC_IO_LIB ${LIBEVENT_DIR}/lib/event${LIB_SUFFIX}) else() set(NATS_ASYNC_IO_LIB ${LIBEVENT_DIR}/lib/libevent${LIB_SUFFIX} ${LIBEVENT_DIR}/lib/libevent_pthreads${LIB_SUFFIX}) endif() else() set(NATS_ASYNC_IO_LIB event) if(UNIX) list(APPEND NATS_ASYNC_IO_LIB event_pthreads) endif() endif() endif() else() set(buildExample ON) endif() if(buildExample) # Build the executable add_executable(${exampleexe} ${PROJECT_SOURCE_DIR}/examples/${examples_src}) # Link if(NATS_BUILD_STATIC_EXAMPLES) target_link_libraries(${exampleexe} nats_static ${NATS_EXTRA_LIB} ${NATS_ASYNC_IO_LIB}) else() target_link_libraries(${exampleexe} nats ${NATS_EXTRA_LIB} ${NATS_ASYNC_IO_LIB}) endif() endif() endforeach() ``` -------------------------------- ### Install NATS libraries and headers Source: https://github.com/nats-io/nats.c/blob/main/README.md Command to install the built static and shared libraries, and public headers. ```bash make install ``` -------------------------------- ### NATS.c Stan Examples CMakeLists.txt Source: https://github.com/nats-io/nats.c/blob/main/examples/stan/CMakeLists.txt This CMakeLists.txt file configures the build process for the NATS.c Streaming (STAN) examples. It includes logic for conditional building based on NATS_BUILD_EXAMPLES and NATS_BUILD_WITH_TLS, finds necessary include directories, and iterates through all .c files in the directory to create executables. ```cmake if(NOT NATS_BUILD_EXAMPLES) return() endif() # We need this directory to build the examples include_directories(${PROJECT_SOURCE_DIR}/src) include_directories(${PROJECT_SOURCE_DIR}/examples/stan) # Get all the .c files in the examples directory file(GLOB EXAMPLES_SOURCES RELATIVE ${PROJECT_SOURCE_DIR}/examples/stan *.c) if(NATS_BUILD_WITH_TLS) include_directories(${OPENSSL_INCLUDE_DIR}) endif(NATS_BUILD_WITH_TLS) # For each file... foreach(examples_src ${EXAMPLES_SOURCES}) # Remove the suffix so that it becomes the executable name string(REPLACE ".c" "" examplename ${examples_src}) set(exampleexe "stan-${examplename}") # Build the executable add_executable(${exampleexe} ${PROJECT_SOURCE_DIR}/examples/stan/${examples_src}) # Link if(NATS_BUILD_STATIC_EXAMPLES) target_link_libraries(${exampleexe} nats_static ${NATS_EXTRA_LIB}) else() target_link_libraries(${exampleexe} nats ${NATS_EXTRA_LIB}) endif() endforeach() ``` -------------------------------- ### Object Store Configuration Example Source: https://github.com/nats-io/nats.c/blob/main/doc/html/group__types_group.html This example demonstrates how to initialize and configure an object store using the objStoreConfig structure, and then use it to create an object store. ```c objStore *obs = NULL; objStoreConfig cfg; objStoreConfig_Init(&cfg); cfg.Bucket = "TEST"; cfg.Description = "Testing ObjectStore"; cfg.Storage = js_MemoryStorage; cfg.TTL = 10000; // 10 seconds cfg.MaxBytes = 1024*1024*1024; cfg.Metadata.List = (const char*[4]){"field1", "value1", "field2", "value2"}; cfg.Metadata.Count = 2; ``` -------------------------------- ### Full TLS/SSL Configuration Example Source: https://github.com/nats-io/nats.c/blob/main/README.md Example demonstrating a comprehensive TLS/SSL configuration including server hostname, CA, client certificates, and ciphers. ```c // Create an options object. natsOptions_Create(&opts); // Set the secure flag. natsOptions_SetSecure(opts, true); // For a server with a trusted chain built into the client host, simply designate the server name that is expected. Without this call, the server certificate is still verified, but not the // hostname. natsOptions_SetExpectedHostname(opts, "localhost"); // Instead, if you are using a self-signed cert and need to load in the CA. natsOptions_LoadCATrustedCertificates(opts, caCertFileName); // If the server requires client certificates, provide them along with the // private key, all in one call. natsOptions_LoadCertificatesChain(opts, certChainFileName, privateKeyFileName); // You can also specify preferred ciphers if you want. natsOptions_SetCiphers(opts, "-ALL:HIGH"); // Then simply pass the options object to the connect call: natsConnection_Connect(&nc, opts); // That's it! On success you will have a secure connection with the server! ``` -------------------------------- ### Example Usage of js_PublishAsyncGetPendingList Source: https://github.com/nats-io/nats.c/blob/main/doc/html/group__js_pub_group.html Example demonstrating how to retrieve pending messages, decide whether to resend them, and then manage the pending list. ```c natsMsgList pending; s = js_PublishAsyncGetPendingList(&pending, js); if (s == NATS_OK) { int i; for (i=0; i $) install(TARGETS nats EXPORT cnats-targets DESTINATION ${NATS_LIBDIR}) install(EXPORT cnats-targets NAMESPACE cnats:: FILE cnats-config.cmake DESTINATION ${NATS_LIBDIR}/cmake/cnats) install(FILES "${PROJECT_BINARY_DIR}/cnats-config-version.cmake" DESTINATION ${NATS_LIBDIR}/cmake/cnats) endif(NATS_BUILD_LIB_SHARED) ``` -------------------------------- ### Object Store Put Example Source: https://github.com/nats-io/nats.c/blob/main/doc/html/group__obs_group.html Example demonstrating how to use objStore_Put, objStorePut_Add, and objStorePut_Complete to upload an object. ```c objStoreMeta meta; objStorePut *put = NULL; objStoreInfo *info = NULL; objStoreMeta_Init(&meta); meta.Name = "test"; s = objStore_Put(&put, obs, &meta); if (s == NATS_OK) { natsStatus addSts = NATS_OK; while ((addSts == NATS_OK) && hasMoreDataToAdd) { // Get some data from somewhere... addSts = objStorePut_Add(put, data, dataLen); // If data needs to be freed, it is safe to do it after the "Add" call. ... } // We are done adding data, call "Complete". We should invoke this even // if there were issues adding data. The call will then purge partial chunks. // The last param is the timeout for operation to complete, here using 3 seconds. s = objStorePut_Complete(&info, put, 3000); } // At this point, the "put" operation is complete. On success, we would have an `info` // variable that can be inspected. If not needed, `NULL` should have been passed to // the `objStorePut_Complete` call. if (s == NATS_OK) { // Inspect the info if needed. } // Now we need to destroy both object. No need to check for `NULL` (as long as you properly initialized them to `NULL`) since the calls internally check for that. objStoreInfo_Destroy(info); objStorePut_Destroy(put); ... ``` -------------------------------- ### Example Signature Callback Implementation Source: https://github.com/nats-io/nats.c/blob/main/README.md An example implementation of a signature callback using `nats_Sign()` to sign a nonce with a provided seed. ```c natsStatus mySignatureCb( char **customErrTxt, unsigned char **signature, int *signatureLength, const char *nonce, void *closure) { // This approach requires to provide the seed (private key). // Hardcoding it in the application (like in this example) may not be really safe. return nats_Sign( "SUACSSL3UAHUDXKFSNVUZRF5UHPMWZ6BFDTJ7M6USDXIEDNPPQYYYCU3VY", nonce, signature, signatureLength); } ``` -------------------------------- ### jsStreamConfig Example Source: https://github.com/nats-io/nats.c/blob/main/doc/html/group__types_group.html Example of initializing and configuring a jsStreamConfig object. ```c jsStreamConfig sc; jsPlacement p; jsStreamSource m; jsExternalStream esm; jsStreamSource s1; jsStreamSource s2; jsExternalStream esmS2; const char *subjects[] = {"foo", "bar"}; const char *tags[] = {"tag1", "tag2"}; jsStreamSource *sources[] = {&s1, &s2}; jsRePublish rp; jsStreamConfig_Init(&sc); jsPlacement_Init(&p); p.Cluster = "MyCluster"; p.Tags = tags; p.TagsLen = 2; jsStreamSource_Init(&m); m.Name = "AStream"; m.OptStartSeq = 100; m.FilterSubject = "foo"; jsExternalStream_Init(&esm); esm.APIPrefix = "mirror.prefix."; esm.DeliverPrefix = "deliver.prefix."; m.External = &esm; ``` -------------------------------- ### pkg-config Configuration Source: https://github.com/nats-io/nats.c/blob/main/CMakeLists.txt Configures pkg-config files for installation on Unix-like systems, handling absolute vs. relative install directories. ```cmake if(UNIX) # Handle absolute vs relative install dirs for pkg-config. # GNUInstallDirs may produce absolute paths (e.g. on NixOS), in which case # we must not prepend ${prefix}/. if(IS_ABSOLUTE "${CMAKE_INSTALL_LIBDIR}") set(PKGCONFIG_LIBDIR "${CMAKE_INSTALL_LIBDIR}") else() set(PKGCONFIG_LIBDIR "\${prefix}/${CMAKE_INSTALL_LIBDIR}") endif() if(IS_ABSOLUTE "${CMAKE_INSTALL_INCLUDEDIR}") set(PKGCONFIG_INCLUDEDIR "${CMAKE_INSTALL_INCLUDEDIR}") else() set(PKGCONFIG_INCLUDEDIR "\${prefix}/${CMAKE_INSTALL_INCLUDEDIR}") endif() configure_file( ${PROJECT_SOURCE_DIR}/src/libnats.pc.in ${PROJECT_BINARY_DIR}/libnats.pc @ONLY ) install ( FILES "${PROJECT_BINARY_DIR}/libnats.pc" DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig") endif(UNIX) ``` -------------------------------- ### objStore_GetString Example Source: https://github.com/nats-io/nats.c/blob/main/doc/html/group__obs_group.html This example demonstrates how to retrieve an object from the object store as a string. It initializes options, calls objStore_GetString, and handles the result, including freeing the allocated memory. ```c objStoreOptions o; objStoreOptions_Init(&o); s = objStore_GetString(&str, obs, "myobject", &o); if (s == NATS_OK) { // Do something with the string ... // It is the user responsibility to free the memory. free(str); } ... ``` -------------------------------- ### natsHeader_Keys Example Source: https://github.com/nats-io/nats.c/blob/main/doc/html/group__header_group.html Example demonstrating how to retrieve all header keys, process them, and free the returned array. ```c const char* *keys = NULL; int count = 0; s = natsMsgHeader_Keys(h, &keys, &count); if (s == NATS_OK) { // do something with the keys // then free the array of pointers. free((void*) keys); } ``` -------------------------------- ### KeyValue Management - Create KeyValue Store Source: https://github.com/nats-io/nats.c/blob/main/README.md Example of how to create a KeyValue store. ```c jsCtx *js = NULL; kvStore *kv = NULL; kvConfig kvc; // Assume we got a JetStream context in `js`... kvConfig_Init(&kvc); kvc.Bucket = "KVS"; kvc.History = 10; s = js_CreateKeyValue(&kv, js, &kvc); // Do some stuff... // This is to free the memory used by `kv` object, // not delete the KeyValue store in the server kvStore_Destroy(kv); ``` -------------------------------- ### natsHeader_Values Example Source: https://github.com/nats-io/nats.c/blob/main/doc/html/group__header_group.html Example demonstrating how to retrieve multiple values for a given key using natsHeader_Values and how to free the returned array. ```c const char* *values = NULL; int count = 0; s = natsHeader_Values(h, "My-Key", &values, &count); if (s == NATS_OK) { // do something with the values // then free the array of pointers. free((void*) values); } ``` -------------------------------- ### jsDirectGetMsgOptions_Init Source: https://github.com/nats-io/nats.c/blob/main/doc/html/group__js_assets_group.html Initializes a direct get message options structure. ```c NATS_EXTERN natsStatus jsDirectGetMsgOptions_Init( jsDirectGetMsgOptions *opts ) ``` -------------------------------- ### js_GetStreamInfo Example Usage Source: https://github.com/nats-io/nats.c/blob/main/doc/html/group__js_assets_group.html Example of how to get detailed information about deleted messages by setting the jsOptions. ```c jsOptions o; jsOptions_Init(&o); o.Stream.Info.DeletedDetails = true; js_GetStreamInfo(&si, js, "MY_STREAM", &o, &jerr); ``` -------------------------------- ### KeyValue Get Entry Source: https://github.com/nats-io/nats.c/blob/main/README.md Provides an example of how to retrieve an entry for a given key from the KeyValue store and access its string value. It also shows how to destroy the entry object. ```c kvStore *kv = NULL; kvEntry *e = NULL; // Assume we got a kvStore... s = kvStore_Get(&e, kv, "MY_KEY"); // Then we can get some fields from the entry: printf("Key value: %s\n", kvEntry_ValueString(e)); // Once done with the entry, we need to destroy it to release memory. // This is NOT deleting the key from the server. kvEntry_Destroy(e); ``` -------------------------------- ### Start CMake GUI on Windows Source: https://github.com/nats-io/nats.c/blob/main/README.md Command to launch the CMake GUI for configuring the build on Windows. ```bash c:\program files (x86)\CMake\bin\cmake-gui.exe ``` -------------------------------- ### Stream Source Initialization and Configuration Source: https://github.com/nats-io/nats.c/blob/main/doc/html/group__types_group.html Example demonstrating the initialization and configuration of stream sources and external stream sources. ```c jsStreamSource_Init(&s1); s1.Name = "StreamOne"; s1.OptStartSeq = 10; s1.FilterSubject = "stream.one"; jsStreamSource_Init(&s2); s2.Name = "StreamTwo"; s2.FilterSubject = "stream.two"; jsExternalStream_Init(&esmS2); esmS2.APIPrefix = "mirror.prefix."; esmS2.DeliverPrefix = "deliver.prefix."; s2.External = &esmS2; ``` -------------------------------- ### Initial CMake configuration Source: https://github.com/nats-io/nats.c/blob/main/README.md Command to configure the build using CMake for the first time. ```bash cmake .. ``` -------------------------------- ### natsMsgHeader_Keys Example Source: https://github.com/nats-io/nats.c/blob/main/doc/html/group__msg_group.html Example of how to retrieve all header keys from a message and then free the returned array. ```c const char* *keys = NULL; int count = 0; s = natsMsgHeader_Keys(msg, &keys, &count); if (s == NATS_OK) { // do something with the keys // then free the array of pointers. free((void*) keys); } ``` -------------------------------- ### Streaming Subscriptions with Options Source: https://github.com/nats-io/nats.c/blob/main/README.md Illustrates how to create NATS Streaming subscriptions with various options to control message delivery, such as starting with the last received message, delivering all available messages, starting at a specific sequence number, or starting at a specific time delta. ```c // Create a Subscription Options: stanSubOptions *subOpts = NULL; stanSubOptions_Create(&subOpts); // Subscribe starting with most recently published value stanSubOptions_StartWithLastReceived(subOpts); // OR: Receive all stored messages stanSubOptions_DeliverAllAvailable(subOpts); // OR: Receive messages starting at a specific sequence number stanSubOptions_StartAtSequence(subOpts, 22); // OR: Start at messages that were stored 30 seconds ago. Value is expressed in milliseconds. stanSubOptions_StartAtTimeDelta(subOpts, 30000); // Create the subscription with options stanConnection_Subscribe(&sub, sc, "foo", onMsg, NULL, subOpts); ``` -------------------------------- ### Versionning and Documentation Configuration Source: https://github.com/nats-io/nats.c/blob/main/CMakeLists.txt Sets version variables and configures package versioning and documentation generation files. ```cmake #------------ # Versionning and Doc set(NATS_VERSION_MAJOR 3) set(NATS_VERSION_MINOR 13) set(NATS_VERSION_PATCH 0) set(NATS_VERSION_SUFFIX "-beta") set(NATS_VERSION_REQUIRED_NUMBER 0x030B00) write_basic_package_version_file( "${PROJECT_BINARY_DIR}/cnats-config-version.cmake" COMPATIBILITY SameMinorVersion VERSION ${NATS_VERSION_MAJOR}.${NATS_VERSION_MINOR}.${NATS_VERSION_PATCH}${NATS_VERSION_SUFFIX}) if(NATS_UPDATE_VERSION OR NATS_UPDATE_DOC) configure_file( ${CMAKE_CURRENT_SOURCE_DIR}/src/version.h.in ${CMAKE_CURRENT_SOURCE_DIR}/src/version.h @ONLY) configure_file( ${CMAKE_SOURCE_DIR}/doc/Doxyfile.NATS.Client.in ${CMAKE_SOURCE_DIR}/doc/DoxyFile.NATS.Client @ONLY) endif(NATS_UPDATE_VERSION OR NATS_UPDATE_DOC) #------------ ``` -------------------------------- ### natsMsgHeader_Values Example Source: https://github.com/nats-io/nats.c/blob/main/doc/html/group__msg_group.html Example of how to retrieve all header values associated with a given key and then free the returned array. ```c const char* *values = NULL; int count = 0; s = natsMsgHeader_Values(msg, "My-Key", &values, &count); if (s == NATS_OK) { // do something with the values // then free the array of pointers. free((void*) values); } ``` -------------------------------- ### Stream Configuration and Addition Source: https://github.com/nats-io/nats.c/blob/main/doc/html/group__types_group.html Example showing the configuration of a stream with various options and its addition to the NATS JetStream context. ```c sc.Name = "MyStream"; sc.Subjects = subjects; sc.SubjectsLen = 2; sc.Retention = js_InterestPolicy; sc.Replicas = 3; sc.Placement = &p; sc.Mirror = &m; sc.Sources = sources; sc.SourcesLen = 2; // For RePublish subject: jsRePublish_Init(&rp); rp.Source = ">"; rp.Destination = "RP.>"; sc.RePublish = &rp; s = js_AddStream(&si, js, &sc, NULL, &jerr); ``` -------------------------------- ### Project Name Source: https://github.com/nats-io/nats.c/blob/main/CMakeLists.txt Defines the project name. ```cmake project(cnats) ``` -------------------------------- ### Header Get Function Source: https://github.com/nats-io/nats.c/blob/main/doc/html/nats_8h_source.html Get the header entry associated with key. ```c NATS_EXTERN natsStatus natsHeader_Get(natsHeader *h, const char *key, const char **value); ``` -------------------------------- ### natsStatistics_GetCounts Source: https://github.com/nats-io/nats.c/blob/main/doc/html/group__stats_group.html Gets the counts out of the statistics object. You can pass NULL to any of the counts you are not interested in getting. ```c #include "nats/nats.h" natsStatistics *stats = NULL; // Assume stats is already created and populated by natsConnection_GetStats() uint64_t inMsgs, inBytes, outMsgs, outBytes, reconnects; natsStatus s = natsStatistics_GetCounts(stats, &inMsgs, &inBytes, &outMsgs, &outBytes, &reconnects); // ... use the counts ... // Remember to destroy the stats object when done: natsStatistics_Destroy(stats); ``` -------------------------------- ### jsFetchRequest_Init() Source: https://github.com/nats-io/nats.c/blob/main/doc/html/group__js_sub_group.html Use this before setting specific fetch options and passing it to natsSubscription_FetchRequest(). ```c natsStatus jsFetchRequest_Init( jsFetchRequest *request ); ``` -------------------------------- ### Initialize Watcher Options Source: https://github.com/nats-io/nats.c/blob/main/doc/html/group__obs_mgt.html Initializes the object store watcher options object. Use this before setting specific options and passing it to objStore_Watch. ```c NATS_EXTERN natsStatus objStoreWatchOptions_Init( objStoreWatchOptions *opts ) ``` -------------------------------- ### Building with EXPERIMENTAL API support Source: https://github.com/nats-io/nats.c/blob/main/README.md Build the nats.c library with experimental API support enabled by defining NATS_WITH_EXPERIMENTAL. ```bash # cd ./build rm CMakeCache.txt cmake .. -DNATS_WITH_EXPERIMENTAL=ON make ``` -------------------------------- ### Minimum TLS/SSL Connection Setup Source: https://github.com/nats-io/nats.c/blob/main/README.md Minimal configuration to establish a secure TLS/SSL connection. ```c // Create an options object. natsOptions_Create(&opts); // Set the secure flag. natsOptions_SetSecure(opts, true); // You may not need this, but suppose that the server certificate // is self-signed and you would normally provide the root CA, but // don't want to. You can disable the server certificate verification // like this: natsOptions_SkipServerVerification(opts, true); // Connect now... natsConnection_Connect(&nc, opts); // That's it! On success you will have a secure connection with the server! ``` -------------------------------- ### Start Position Ignored in Queue Group Source: https://github.com/nats-io/nats.c/blob/main/README.md Demonstrates how a specified start position is ignored when a new member joins an existing queue group. ```c stanSubOptions_Create(&subOpts); stanSubOptions_StartAtSequence(subOpts, 200); stanConnection_QueueSubscribe(&qsub, "foo", "bar", onMsg, NULL, subOpts); ``` -------------------------------- ### Object Store Get Operations Source: https://github.com/nats-io/nats.c/blob/main/doc/html/nats_8h_source.html Functions for getting data from the NATS Object Store. ```c NATS_EXTERN natsStatus objStore_Get(objStoreGet **new_get, objStore *obs, const char *name, objStoreOptions *opts); NATS_EXTERN natsStatus objStoreGet_Info(const objStoreInfo **new_info, objStoreGet *get); NATS_EXTERN natsStatus objStoreGet_Read(bool *done, void **new_data, int *dataLen, objStoreGet *get, int64_t timeout); NATS_EXTERN natsStatus objStoreGet_ReadAll(void **new_data, int *dataLen, objStoreGet *get, int64_t timeout); NATS_EXTERN void objStoreGet_Destroy(objStoreGet *get); ``` -------------------------------- ### Clustered Usage Example Source: https://github.com/nats-io/nats.c/blob/main/README.md Demonstrates how to configure the NATS client to connect to a cluster of servers, including setting reconnect options and callbacks. ```c static char *servers[] = { "nats://localhost:1222", "nats://localhost:1223", "nats://localhost:1224"}; // Setup options to include all servers in the cluster. // We first created an options object, and pass the list of servers, specifying // the number of servers on that list. natsOptions_SetServers(opts, servers, 3); // We could also set the amount to sleep between each reconnect attempt (expressed in // milliseconds), and the number of reconnect attempts. natsOptions_SetMaxReconnect(opts, 5); natsOptions_SetReconnectWait(opts, 2000); // We could also disable the randomization of the server pool natsOptions_SetNoRandomize(opts, true); // Setup a callback to be notified on disconnects... natsOptions_SetDisconnectedCB(opts, disconnectedCb, NULL); // And on reconncet natsOptions_SetReconnectedCB(opts, reconnectedCb, NULL); // This callback could be used to see who we are connected to on reconnect static void reconnectedCb(natsConnection *nc, void *closure) { // Define a buffer to receive the url char buffer[64]; buffer[0] = '\0'; natsConnection_GetConnectedUrl(nc, buffer, sizeof(buffer)); printf("Got reconnected to: %s\n", buffer); } ```