Skip to content

nginx microservices with dynamic linked application

Taymindis Woon edited this page Nov 17, 2018 · 15 revisions

nginx-c-function has provided the following functions to achieve the communication with other application service. These functions are built in on top of nginx, it is purely based on nginx.

extern u_char* ngx_http_c_func_get_header(ngx_http_c_func_ctx_t *ctx, const char*key);
extern void* ngx_http_c_func_get_query_param(ngx_http_c_func_ctx_t *ctx, const char *key);
extern int ngx_http_c_func_add_header_in(ngx_http_c_func_ctx_t *ctx, const char *key, size_t keylen, const char *value, size_t val_len );
extern void ngx_http_c_func_write_resp(
    ngx_http_c_func_ctx_t *ctx,
    uintptr_t status_code,
    const char* status_line,
    const char* content_type,
    const char* resp_content,
    size_t resp_len
);

For every nginx-c-function linked application, you may apply the functions above to achieve the inter communication between the services. For example authenthication, you may get the userId,token, and etc from headers.

void my_simple_authentication(ngx_http_c_func_ctx_t *ctx) {

    ngx_http_c_func_log_info(ctx, "Authenticating");
    char *userId = (char*) ngx_http_c_func_get_header(ctx, "userId");
    char *userPass = (char*) ngx_http_c_func_get_header(ctx, "userPass");
    char* userInfoJsonStr = processing(userId, userPass);

    // Once success, you may pass your info to other instance to continue your process 
    ngx_http_c_func_add_header_in(ctx, "userInfo", sizeof("userInfo")-1, userInfoJsonStr, strlen(userInfoJsonStr));
}

From nginx config, you can setup many way to routing your service to another. For example based on the code login above

ngx_http_c_func_link_lib "/home/taymindis/github/nginx-c-function/t/libcfuntest.so";
location /backend {
    return 200 "Welcome ${arg_userName}";
}
location = /auth {
    internal;
    ngx_http_c_func_call "my_simple_authentication";
}
location = /my_simple_authentication {
  ngx_http_c_func_add_req_header userId $arg_userId;
  ngx_http_c_func_add_req_header userPass $arg_userPass;
  auth_request /auth;
  proxy_pass http://127.0.0.1:${server_port}/backend?userName=$http_userName;
}

There are a lot of directive which able to support routing service, such as:

proxy directive

mirror directirve

auth_request

addition directive

to be continue how it works with mirror and addition directive

Clone this wiki locally