From 71cdc71aca4f14dafae924e379bf0efc8b057ba7 Mon Sep 17 00:00:00 2001 From: Michael McVady Date: Fri, 13 May 2022 19:45:23 -0500 Subject: Flesh out toy envvar config parser --- sandbox/envvar/Makefile | 1 + sandbox/envvar/envvar.c | 68 +++++++++++++++++++++++++++++++++++++------------ 2 files changed, 53 insertions(+), 16 deletions(-) (limited to 'sandbox/envvar') diff --git a/sandbox/envvar/Makefile b/sandbox/envvar/Makefile index ae4c74e..9305ccf 100644 --- a/sandbox/envvar/Makefile +++ b/sandbox/envvar/Makefile @@ -1,6 +1,7 @@ .PHONY: run clean CC = gcc +# CFLAGS = -g -Wall -Wextra -Wmissing-declarations -Wshadow -Wstrict-prototypes -Wmissing-prototypes -Wpointer-arith -Wcast-qual -Wsign-compare CFLAGS = -g -Wall -Wmissing-declarations -Wshadow -Wstrict-prototypes -Wmissing-prototypes -Wpointer-arith -Wcast-qual -Wsign-compare all: envvar diff --git a/sandbox/envvar/envvar.c b/sandbox/envvar/envvar.c index bbcb1c9..8ef3013 100644 --- a/sandbox/envvar/envvar.c +++ b/sandbox/envvar/envvar.c @@ -1,24 +1,57 @@ #include #include +#include int main(int argc, char *argv[]) { - const char* pg_dbname = getenv("POSTGRES_DBNAME"); - const char* pg_host = getenv("POSTGRES_HOST"); - const char* pg_password = getenv("POSTGRES_PASSWORD"); - const char* pg_port = getenv("POSTGRES_PORT"); - const char* pg_user = getenv("POSTGRES_USER"); - - printf("POSTGRES_DBNAME: %s\n", (pg_dbname != NULL) ? pg_dbname : "undefined"); - printf("POSTGRES_HOST: %s\n", (pg_host != NULL) ? pg_host : "undefined"); - printf("POSTGRES_PASSWORD: %s\n", (pg_password != NULL) ? pg_password : "undefined"); - printf("POSTGRES_PORT: %s\n", (pg_port != NULL) ? pg_port : "undefined"); - printf("POSTGRES_USER: %s\n", (pg_user != NULL) ? pg_user : "undefined"); - - char *config = "host=%s port=%s user=%s password=%s dbname=%s sslmode=disable\n"; - - sprintf( - config, + char pg_dbname[128] = {0}; + char pg_host[128] = {0}; + char pg_password[128] = {0}; + char pg_port[8] = {0}; + char pg_user[128] = {0}; + + const char* env; + + env = getenv("POSTGRES_DBNAME"); + if (env != NULL) + { + strncpy(pg_dbname, env, sizeof(pg_dbname)); + } + + env = getenv("POSTGRES_HOST"); + if (env != NULL) + { + strncpy(pg_host, env, sizeof(pg_host)); + } + + env = getenv("POSTGRES_PASSWORD"); + if (env != NULL) + { + strncpy(pg_password, env, sizeof(pg_password)); + } + + env = getenv("POSTGRES_PORT"); + if (env != NULL) + { + strncpy(pg_port, env, sizeof(pg_port)); + } + + env = getenv("POSTGRES_USER"); + if (env != NULL) + { + strncpy(pg_user, env, sizeof(pg_user)); + } + + char *config_fmt = "host=%s port=%s user=%s password=%s dbname=%s sslmode=disable"; + + printf(config_fmt, pg_host, pg_port, pg_user, pg_password, pg_dbname); + printf("\n"); + + char sqladdr[2048]; + snprintf( + sqladdr, + sizeof(sqladdr), + config_fmt, pg_host, pg_port, pg_user, @@ -26,4 +59,7 @@ int main(int argc, char *argv[]) pg_dbname ); + printf("%s", sqladdr); + printf("\n"); + } -- cgit v1.2.3