From 6b7faf1899e37a8ceedc427ad1666630a4312567 Mon Sep 17 00:00:00 2001 From: Shah Ismail Date: Thu, 10 Sep 2020 15:27:23 +0300 Subject: [PATCH 01/22] Basic cleaning --- Makefile | 10 ++++++++++ main.go => cmd/genityapp/main.go | 15 +++++---------- db.env | 3 +++ db_dump | 4 ---- ddl_01.sql | 1 + dml_01.sql | 1 + docker-compose.yml | 22 +++++++++++++--------- api.go => genityapp/api.go | 0 web.env | 6 ++++++ 9 files changed, 39 insertions(+), 23 deletions(-) create mode 100644 Makefile rename main.go => cmd/genityapp/main.go (78%) create mode 100644 db.env delete mode 100644 db_dump create mode 100644 ddl_01.sql create mode 100644 dml_01.sql rename api.go => genityapp/api.go (100%) create mode 100644 web.env diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..0e523d5 --- /dev/null +++ b/Makefile @@ -0,0 +1,10 @@ +export NAME=genityapp + +build: + docker-compose build + +run: build + docker-compose up + +build-binary: + GOOS=linux GOARCH=amd64 go build \ No newline at end of file diff --git a/main.go b/cmd/genityapp/main.go similarity index 78% rename from main.go rename to cmd/genityapp/main.go index af6072a..10f60ef 100644 --- a/main.go +++ b/cmd/genityapp/main.go @@ -22,11 +22,11 @@ func main() { initDb() defer db.Close() - http.HandleFunc("/api/users", UserGetHandler) - http.HandleFunc("/api/user", UserPostHandler) + http.HandleFunc("/get-data", UserGetHandler) + http.HandleFunc("/post-data", UserPostHandler) - fmt.Println("Listening on :8080") - log.Fatal(http.ListenAndServe(":8080", nil)) + fmt.Println("Listening on :5000") + log.Fatal(http.ListenAndServe(":5000", nil)) } @@ -48,16 +48,11 @@ func initDb() { panic(err) } fmt.Println("Successfully connected!") - - - - - } func dbConfig() map[string]string { conf := make(map[string]string) - conf[dbhost] = "poc-golang-postgres-docker_db_1" + conf[dbhost] = "genitywebapp_db_1" conf[dbport] = "5432" conf[dbuser] = "root_user" conf[dbpass] = "shahzad12" diff --git a/db.env b/db.env new file mode 100644 index 0000000..b81c7e3 --- /dev/null +++ b/db.env @@ -0,0 +1,3 @@ +POSTGRES_DB=db_genity +POSTGRES_USER=root_user +POSTGRES_PASSWORD=shahzad12 \ No newline at end of file diff --git a/db_dump b/db_dump deleted file mode 100644 index cfacdf5..0000000 --- a/db_dump +++ /dev/null @@ -1,4 +0,0 @@ -CREATE TABLE users ( user_id serial PRIMARY KEY, title VARCHAR ( 50 ) UNIQUE NOT NULL, created_on TIMESTAMP NOT NULL); -INSERT INTO users (title,created_on) VALUES('shahzad','2013-06-01'); - - diff --git a/ddl_01.sql b/ddl_01.sql new file mode 100644 index 0000000..e9b8a1d --- /dev/null +++ b/ddl_01.sql @@ -0,0 +1 @@ +CREATE TABLE users (user_id serial PRIMARY KEY, title VARCHAR ( 50 ) UNIQUE NOT NULL, created_on TIMESTAMP NOT NULL); \ No newline at end of file diff --git a/dml_01.sql b/dml_01.sql new file mode 100644 index 0000000..0ee150a --- /dev/null +++ b/dml_01.sql @@ -0,0 +1 @@ +INSERT INTO users (title,created_on) VALUES('shahzad','2013-06-01'); \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml index 22eb0de..5d74d84 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -2,21 +2,25 @@ version: '3' services: db: image: postgres - environment: - POSTGRES_DB: db_genity - POSTGRES_USER: root_user - POSTGRES_PASSWORD: shahzad12 + env_file: + - ./db.env volumes: - - db_postgres:/var/lib/postgresql/data - ports: - - "5436:5432" + - ./db_postgres:/var/lib/postgresql/data + - ./ddl_01.sql:/docker-entrypoint-initdb.d/10_schema.sql + - ./dml_01.sql:/docker-entrypoint-initdb.d/20_insert.sql + expose: + - "5432" + restart: always networks: - genity_network - app: + web: build: "" command: [ "go", "run", "main.go","api.go"] + env_file: + - ./web.env ports: - - "8080:8080" + - "5000:5000" + restart: always depends_on: - db links: diff --git a/api.go b/genityapp/api.go similarity index 100% rename from api.go rename to genityapp/api.go diff --git a/web.env b/web.env new file mode 100644 index 0000000..ada0a56 --- /dev/null +++ b/web.env @@ -0,0 +1,6 @@ +COMPOSE_PROJECT_NAME=genitywebapp +dbhost=genityapp_db_1" +dbport=5432 +dbuser=root_user +dbpass=shahzad12 +dbname=db_genity \ No newline at end of file From c20c3adf6d340e2e29a586682a5450602c4454ab Mon Sep 17 00:00:00 2001 From: Shah Ismail Date: Fri, 11 Sep 2020 12:13:09 +0300 Subject: [PATCH 02/22] Project dir restructing WIP --- Makefile | 6 +-- cmd/genityapp/main.go | 2 + db.env | 3 -- ddl_01.sql | 1 - dml_01.sql | 1 - docker-compose.yml | 12 +++-- genityapp/api.go | 100 ------------------------------------------ go.mod | 2 +- web.env | 6 --- 9 files changed, 11 insertions(+), 122 deletions(-) delete mode 100644 db.env delete mode 100644 ddl_01.sql delete mode 100644 dml_01.sql delete mode 100644 genityapp/api.go delete mode 100644 web.env diff --git a/Makefile b/Makefile index 0e523d5..4aaf8b8 100644 --- a/Makefile +++ b/Makefile @@ -1,5 +1,3 @@ -export NAME=genityapp - build: docker-compose build @@ -7,4 +5,6 @@ run: build docker-compose up build-binary: - GOOS=linux GOARCH=amd64 go build \ No newline at end of file + GOOS=linux GOARCH=amd64 go build + +.PHONY: build-binary run build diff --git a/cmd/genityapp/main.go b/cmd/genityapp/main.go index 10f60ef..8c53afb 100644 --- a/cmd/genityapp/main.go +++ b/cmd/genityapp/main.go @@ -6,6 +6,8 @@ import ( _ "github.com/lib/pq" "log" "net/http" + + "genityapi" ) var db *sql.DB diff --git a/db.env b/db.env deleted file mode 100644 index b81c7e3..0000000 --- a/db.env +++ /dev/null @@ -1,3 +0,0 @@ -POSTGRES_DB=db_genity -POSTGRES_USER=root_user -POSTGRES_PASSWORD=shahzad12 \ No newline at end of file diff --git a/ddl_01.sql b/ddl_01.sql deleted file mode 100644 index e9b8a1d..0000000 --- a/ddl_01.sql +++ /dev/null @@ -1 +0,0 @@ -CREATE TABLE users (user_id serial PRIMARY KEY, title VARCHAR ( 50 ) UNIQUE NOT NULL, created_on TIMESTAMP NOT NULL); \ No newline at end of file diff --git a/dml_01.sql b/dml_01.sql deleted file mode 100644 index 0ee150a..0000000 --- a/dml_01.sql +++ /dev/null @@ -1 +0,0 @@ -INSERT INTO users (title,created_on) VALUES('shahzad','2013-06-01'); \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml index 5d74d84..e91e076 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,13 +1,12 @@ -version: '3' +version: "3.8" services: db: image: postgres - env_file: - - ./db.env + env_file: ./configs/db.env volumes: - ./db_postgres:/var/lib/postgresql/data - - ./ddl_01.sql:/docker-entrypoint-initdb.d/10_schema.sql - - ./dml_01.sql:/docker-entrypoint-initdb.d/20_insert.sql + - ./scripts/db/ddl_01.sql:/docker-entrypoint-initdb.d/10_schema.sql + - ./scripts/db/dml_01.sql:/docker-entrypoint-initdb.d/20_insert.sql expose: - "5432" restart: always @@ -16,8 +15,7 @@ services: web: build: "" command: [ "go", "run", "main.go","api.go"] - env_file: - - ./web.env + env_file: ./configs/web.env ports: - "5000:5000" restart: always diff --git a/genityapp/api.go b/genityapp/api.go deleted file mode 100644 index 4bcc3dc..0000000 --- a/genityapp/api.go +++ /dev/null @@ -1,100 +0,0 @@ -package main - -import ( - "encoding/json" - "fmt" - "net/http" - "time" -) - -type User struct { - UserID int - Title string - CreatedOn time.Time -} - -type Users struct { - users []User -} - -func UserGetHandler(w http.ResponseWriter, req *http.Request) { - if req.Method == "GET" { - users := Users{} - - err := queryRepos(&users) - if err != nil { - http.Error(w, err.Error(), 500) - return - } - - out, err := json.Marshal(users.users) - if err != nil { - http.Error(w, err.Error(), 500) - return - } - - fmt.Fprintf(w, string(out)) - } else { - fmt.Fprintf(w, "Sorry, only Get methods are supported for thus api.") - } -} - -func UserPostHandler(w http.ResponseWriter, req *http.Request) { - if req.Method == "POST" { - if err := req.ParseForm(); err != nil { - fmt.Fprintf(w, "ParseForm() err: %v", err) - return - } - title := req.FormValue("title") - sqlInsert := ` -INSERT INTO users (title, created_on) -VALUES ($1, $2) -RETURNING user_id` - if len(title) > 0 { - user_id := 0 - row := db.QueryRow(sqlInsert, title, time.Now()) - err := row.Scan(&user_id) - if err != nil { - panic(err) - } - fmt.Fprintf(w, "user creted") - } else { - fmt.Fprintf(w, "Invalid data") - } - } else { - fmt.Fprintf(w, "Sorry, only POST methods are supported for thus api.") - } -} - -func queryRepos(users *Users) error { - rows, err := db.Query(` - SELECT - user_id, - title, - created_on - - FROM users; - `) - if err != nil { - return err - } - defer rows.Close() - for rows.Next() { - user := User{} - err = rows.Scan( - &user.UserID, - &user.Title, - &user.CreatedOn, - ) - if err != nil { - return err - } - users.users = append(users.users, user) - } - - err = rows.Err() - if err != nil { - return err - } - return nil -} diff --git a/go.mod b/go.mod index 3b7747b..5b6e8f7 100644 --- a/go.mod +++ b/go.mod @@ -1,4 +1,4 @@ -module genity-code-review +module genityapi go 1.14 diff --git a/web.env b/web.env deleted file mode 100644 index ada0a56..0000000 --- a/web.env +++ /dev/null @@ -1,6 +0,0 @@ -COMPOSE_PROJECT_NAME=genitywebapp -dbhost=genityapp_db_1" -dbport=5432 -dbuser=root_user -dbpass=shahzad12 -dbname=db_genity \ No newline at end of file From da0643ee96bd860dd51ca2ec49cea27b0df4c8b5 Mon Sep 17 00:00:00 2001 From: Shah Ismail Date: Fri, 11 Sep 2020 12:13:41 +0300 Subject: [PATCH 03/22] Project dir restructing WIP 2 --- api.go | 100 ++++++++++++++++++++++++++++++++++ build/Dockerfile | 8 +++ configs/db.env | 3 + configs/web.env | 6 ++ internal/app/genityapp/api.go | 100 ++++++++++++++++++++++++++++++++++ main.go | 61 +++++++++++++++++++++ scripts/db/ddl_01.sql | 1 + scripts/db/dml_01.sql | 1 + 8 files changed, 280 insertions(+) create mode 100644 api.go create mode 100644 build/Dockerfile create mode 100644 configs/db.env create mode 100644 configs/web.env create mode 100644 internal/app/genityapp/api.go create mode 100644 main.go create mode 100644 scripts/db/ddl_01.sql create mode 100644 scripts/db/dml_01.sql diff --git a/api.go b/api.go new file mode 100644 index 0000000..4bcc3dc --- /dev/null +++ b/api.go @@ -0,0 +1,100 @@ +package main + +import ( + "encoding/json" + "fmt" + "net/http" + "time" +) + +type User struct { + UserID int + Title string + CreatedOn time.Time +} + +type Users struct { + users []User +} + +func UserGetHandler(w http.ResponseWriter, req *http.Request) { + if req.Method == "GET" { + users := Users{} + + err := queryRepos(&users) + if err != nil { + http.Error(w, err.Error(), 500) + return + } + + out, err := json.Marshal(users.users) + if err != nil { + http.Error(w, err.Error(), 500) + return + } + + fmt.Fprintf(w, string(out)) + } else { + fmt.Fprintf(w, "Sorry, only Get methods are supported for thus api.") + } +} + +func UserPostHandler(w http.ResponseWriter, req *http.Request) { + if req.Method == "POST" { + if err := req.ParseForm(); err != nil { + fmt.Fprintf(w, "ParseForm() err: %v", err) + return + } + title := req.FormValue("title") + sqlInsert := ` +INSERT INTO users (title, created_on) +VALUES ($1, $2) +RETURNING user_id` + if len(title) > 0 { + user_id := 0 + row := db.QueryRow(sqlInsert, title, time.Now()) + err := row.Scan(&user_id) + if err != nil { + panic(err) + } + fmt.Fprintf(w, "user creted") + } else { + fmt.Fprintf(w, "Invalid data") + } + } else { + fmt.Fprintf(w, "Sorry, only POST methods are supported for thus api.") + } +} + +func queryRepos(users *Users) error { + rows, err := db.Query(` + SELECT + user_id, + title, + created_on + + FROM users; + `) + if err != nil { + return err + } + defer rows.Close() + for rows.Next() { + user := User{} + err = rows.Scan( + &user.UserID, + &user.Title, + &user.CreatedOn, + ) + if err != nil { + return err + } + users.users = append(users.users, user) + } + + err = rows.Err() + if err != nil { + return err + } + return nil +} diff --git a/build/Dockerfile b/build/Dockerfile new file mode 100644 index 0000000..eab6d63 --- /dev/null +++ b/build/Dockerfile @@ -0,0 +1,8 @@ +FROM golang:alpine as builder + +RUN mkdir -p /go/src/app +WORKDIR /go/src/app + +ADD . /go/src/app + +RUN go get -d -v \ No newline at end of file diff --git a/configs/db.env b/configs/db.env new file mode 100644 index 0000000..b81c7e3 --- /dev/null +++ b/configs/db.env @@ -0,0 +1,3 @@ +POSTGRES_DB=db_genity +POSTGRES_USER=root_user +POSTGRES_PASSWORD=shahzad12 \ No newline at end of file diff --git a/configs/web.env b/configs/web.env new file mode 100644 index 0000000..4625515 --- /dev/null +++ b/configs/web.env @@ -0,0 +1,6 @@ +COMPOSE_PROJECT_NAME=genitywebapp +dbhost=genityapp_db_1 +dbport=5432 +dbuser=root_user +dbpass=shahzad12 +dbname=db_genity \ No newline at end of file diff --git a/internal/app/genityapp/api.go b/internal/app/genityapp/api.go new file mode 100644 index 0000000..214c42e --- /dev/null +++ b/internal/app/genityapp/api.go @@ -0,0 +1,100 @@ +package genityapi + +import ( + "encoding/json" + "fmt" + "net/http" + "time" +) + +type User struct { + UserID int + Title string + CreatedOn time.Time +} + +type Users struct { + users []User +} + +func UserGetHandler(w http.ResponseWriter, req *http.Request) { + if req.Method == "GET" { + users := Users{} + + err := queryRepos(&users) + if err != nil { + http.Error(w, err.Error(), 500) + return + } + + out, err := json.Marshal(users.users) + if err != nil { + http.Error(w, err.Error(), 500) + return + } + + fmt.Fprintf(w, string(out)) + } else { + fmt.Fprintf(w, "Sorry, only Get methods are supported for thus api.") + } +} + +func UserPostHandler(w http.ResponseWriter, req *http.Request) { + if req.Method == "POST" { + if err := req.ParseForm(); err != nil { + fmt.Fprintf(w, "ParseForm() err: %v", err) + return + } + title := req.FormValue("title") + sqlInsert := ` +INSERT INTO users (title, created_on) +VALUES ($1, $2) +RETURNING user_id` + if len(title) > 0 { + user_id := 0 + row := db.QueryRow(sqlInsert, title, time.Now()) + err := row.Scan(&user_id) + if err != nil { + panic(err) + } + fmt.Fprintf(w, "user creted") + } else { + fmt.Fprintf(w, "Invalid data") + } + } else { + fmt.Fprintf(w, "Sorry, only POST methods are supported for thus api.") + } +} + +func queryRepos(users *Users) error { + rows, err := db.Query(` + SELECT + user_id, + title, + created_on + + FROM users; + `) + if err != nil { + return err + } + defer rows.Close() + for rows.Next() { + user := User{} + err = rows.Scan( + &user.UserID, + &user.Title, + &user.CreatedOn, + ) + if err != nil { + return err + } + users.users = append(users.users, user) + } + + err = rows.Err() + if err != nil { + return err + } + return nil +} diff --git a/main.go b/main.go new file mode 100644 index 0000000..10f60ef --- /dev/null +++ b/main.go @@ -0,0 +1,61 @@ +package main + +import ( + "database/sql" + "fmt" + _ "github.com/lib/pq" + "log" + "net/http" +) + +var db *sql.DB + +const ( + dbhost = "DBHOST" + dbport = "DBPORT" + dbuser = "DBUSER" + dbpass = "DBPASS" + dbname = "DBNAME" +) + +func main() { + initDb() + defer db.Close() + + http.HandleFunc("/get-data", UserGetHandler) + http.HandleFunc("/post-data", UserPostHandler) + + fmt.Println("Listening on :5000") + log.Fatal(http.ListenAndServe(":5000", nil)) + +} + + +func initDb() { + config := dbConfig() + var err error + psqlInfo := fmt.Sprintf("postgres://%v:%v@%v:%v/%v?sslmode=disable", + config[dbuser], config[dbpass], + config[dbhost], config[dbport], config[dbname]) + + fmt.Println(psqlInfo) + db, err = sql.Open("postgres", psqlInfo) + if err != nil { + panic(err) + } + err = db.Ping() + if err != nil { + panic(err) + } + fmt.Println("Successfully connected!") +} + +func dbConfig() map[string]string { + conf := make(map[string]string) + conf[dbhost] = "genitywebapp_db_1" + conf[dbport] = "5432" + conf[dbuser] = "root_user" + conf[dbpass] = "shahzad12" + conf[dbname] = "db_genity" + return conf +} diff --git a/scripts/db/ddl_01.sql b/scripts/db/ddl_01.sql new file mode 100644 index 0000000..e9b8a1d --- /dev/null +++ b/scripts/db/ddl_01.sql @@ -0,0 +1 @@ +CREATE TABLE users (user_id serial PRIMARY KEY, title VARCHAR ( 50 ) UNIQUE NOT NULL, created_on TIMESTAMP NOT NULL); \ No newline at end of file diff --git a/scripts/db/dml_01.sql b/scripts/db/dml_01.sql new file mode 100644 index 0000000..0ee150a --- /dev/null +++ b/scripts/db/dml_01.sql @@ -0,0 +1 @@ +INSERT INTO users (title,created_on) VALUES('shahzad','2013-06-01'); \ No newline at end of file From b99e888781f041c26840e375a3603c7411228c32 Mon Sep 17 00:00:00 2001 From: Shah Ismail Date: Fri, 11 Sep 2020 12:30:05 +0300 Subject: [PATCH 04/22] Project dir restructing WIP 2a --- main.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/main.go b/main.go index 10f60ef..2ad1260 100644 --- a/main.go +++ b/main.go @@ -52,7 +52,7 @@ func initDb() { func dbConfig() map[string]string { conf := make(map[string]string) - conf[dbhost] = "genitywebapp_db_1" + conf[dbhost] = "POC-golang-postgres-docker_db_1" conf[dbport] = "5432" conf[dbuser] = "root_user" conf[dbpass] = "shahzad12" From 4c2414fa0a2655721946e2d8f905a3a36954c661 Mon Sep 17 00:00:00 2001 From: Shaz hemani Date: Fri, 11 Sep 2020 17:09:53 +0500 Subject: [PATCH 05/22] issue #1 and #2 --- Makefile | 4 ++-- docker-compose.yml | 4 ++-- main.go | 3 +-- 3 files changed, 5 insertions(+), 6 deletions(-) diff --git a/Makefile b/Makefile index 4aaf8b8..6617c0d 100644 --- a/Makefile +++ b/Makefile @@ -1,8 +1,8 @@ build: docker-compose build -run: build - docker-compose up +run: + COMPOSE_PROJECT_NAME=genitywebapp docker-compose up --build build-binary: GOOS=linux GOARCH=amd64 go build diff --git a/docker-compose.yml b/docker-compose.yml index e91e076..bab9efc 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,10 +1,10 @@ -version: "3.8" +version: "3" services: db: image: postgres env_file: ./configs/db.env volumes: - - ./db_postgres:/var/lib/postgresql/data + - db_postgres:/var/lib/postgresql/data - ./scripts/db/ddl_01.sql:/docker-entrypoint-initdb.d/10_schema.sql - ./scripts/db/dml_01.sql:/docker-entrypoint-initdb.d/20_insert.sql expose: diff --git a/main.go b/main.go index 2ad1260..133d0f4 100644 --- a/main.go +++ b/main.go @@ -30,7 +30,6 @@ func main() { } - func initDb() { config := dbConfig() var err error @@ -52,7 +51,7 @@ func initDb() { func dbConfig() map[string]string { conf := make(map[string]string) - conf[dbhost] = "POC-golang-postgres-docker_db_1" + conf[dbhost] = "genitywebapp_db_1" conf[dbport] = "5432" conf[dbuser] = "root_user" conf[dbpass] = "shahzad12" From aa89c13a3cd28e27b7faff95535c68cabd7c21dd Mon Sep 17 00:00:00 2001 From: Shah Ismail Date: Fri, 11 Sep 2020 17:01:41 +0300 Subject: [PATCH 06/22] Project dir restructing WIP 3 --- Makefile | 6 ++++-- configs/web.env | 1 - 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/Makefile b/Makefile index 6617c0d..9d5de03 100644 --- a/Makefile +++ b/Makefile @@ -1,8 +1,10 @@ +export NAME=genitywebapp + build: docker-compose build -run: - COMPOSE_PROJECT_NAME=genitywebapp docker-compose up --build +run: build + docker-compose up build-binary: GOOS=linux GOARCH=amd64 go build diff --git a/configs/web.env b/configs/web.env index 4625515..97b1942 100644 --- a/configs/web.env +++ b/configs/web.env @@ -1,4 +1,3 @@ -COMPOSE_PROJECT_NAME=genitywebapp dbhost=genityapp_db_1 dbport=5432 dbuser=root_user From 51b1ac1fa3227084f62e28d87b14bfd4c063fcaa Mon Sep 17 00:00:00 2001 From: Shaz hemani Date: Fri, 11 Sep 2020 19:06:41 +0500 Subject: [PATCH 07/22] point 7 8 10 11 --- api.go | 58 ++++++++++++++++++++++++++++++++----------- go.mod | 1 + scripts/db/ddl_01.sql | 3 ++- 3 files changed, 46 insertions(+), 16 deletions(-) diff --git a/api.go b/api.go index 4bcc3dc..ea57ef3 100644 --- a/api.go +++ b/api.go @@ -3,6 +3,7 @@ package main import ( "encoding/json" "fmt" + uuid "github.com/nu7hatch/gouuid" "net/http" "time" ) @@ -19,21 +20,38 @@ type Users struct { func UserGetHandler(w http.ResponseWriter, req *http.Request) { if req.Method == "GET" { + + title, ok := req.URL.Query()["title"] + + if !ok || len(title[0]) < 1 { + http.Error(w, "Url Param 'title' is missing", 400) + return + } + + // Query()["key"] will return an array of items, + // we only want the single item. + userTitle := title[0] + users := Users{} - err := queryRepos(&users) + err := queryRepos(&users, userTitle) if err != nil { http.Error(w, err.Error(), 500) return } - out, err := json.Marshal(users.users) - if err != nil { - http.Error(w, err.Error(), 500) - return - } + if len(users.users) > 0 { - fmt.Fprintf(w, string(out)) + out, err := json.Marshal(users.users) + if err != nil { + http.Error(w, err.Error(), 500) + return + } + + fmt.Fprintf(w, string(out)) + } else { + fmt.Fprintf(w, "User does not exist") + } } else { fmt.Fprintf(w, "Sorry, only Get methods are supported for thus api.") } @@ -45,19 +63,26 @@ func UserPostHandler(w http.ResponseWriter, req *http.Request) { fmt.Fprintf(w, "ParseForm() err: %v", err) return } + + uuid, err := uuid.NewV4() + if err != nil { + http.Error(w, err.Error(), 500) + + } + title := req.FormValue("title") sqlInsert := ` -INSERT INTO users (title, created_on) -VALUES ($1, $2) +INSERT INTO users (title, created_on,uuid) +VALUES ($1, $2, $3) RETURNING user_id` if len(title) > 0 { user_id := 0 - row := db.QueryRow(sqlInsert, title, time.Now()) + row := db.QueryRow(sqlInsert, title, time.Now().Format(time.RFC3339), uuid.String()) err := row.Scan(&user_id) if err != nil { panic(err) } - fmt.Fprintf(w, "user creted") + fmt.Fprintf(w, "user created.") } else { fmt.Fprintf(w, "Invalid data") } @@ -66,15 +91,18 @@ RETURNING user_id` } } -func queryRepos(users *Users) error { - rows, err := db.Query(` +func queryRepos(users *Users, userTitle string) error { + query := ` SELECT user_id, title, created_on - FROM users; - `) + FROM users + WHERE title='` + userTitle + `'; + ` + + rows, err := db.Query(query) if err != nil { return err } diff --git a/go.mod b/go.mod index 5b6e8f7..45c6723 100644 --- a/go.mod +++ b/go.mod @@ -4,4 +4,5 @@ go 1.14 require ( github.com/lib/pq v1.8.0 + github.com/nu7hatch/gouuid v0.0.0-20131221200532-179d4d0c4d8d ) diff --git a/scripts/db/ddl_01.sql b/scripts/db/ddl_01.sql index e9b8a1d..f132c71 100644 --- a/scripts/db/ddl_01.sql +++ b/scripts/db/ddl_01.sql @@ -1 +1,2 @@ -CREATE TABLE users (user_id serial PRIMARY KEY, title VARCHAR ( 50 ) UNIQUE NOT NULL, created_on TIMESTAMP NOT NULL); \ No newline at end of file +CREATE TABLE users (user_id serial PRIMARY KEY, title VARCHAR ( 50 ) UNIQUE NOT NULL, + uuid VARCHAR ( 50 ) UNIQUE NOT NULL, created_on TIMESTAMP NOT NULL); \ No newline at end of file From ec4a40e72fcf644a0b8256230799cdaeeffe89cf Mon Sep 17 00:00:00 2001 From: Shaz hemani Date: Fri, 11 Sep 2020 19:11:00 +0500 Subject: [PATCH 08/22] issue conflict resolved --- Makefile | 2 +- scripts/db/dml_01.sql | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index 9d5de03..7651a95 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,7 @@ export NAME=genitywebapp build: - docker-compose build + COMPOSE_PROJECT_NAME=genitywebapp docker-compose up --build run: build docker-compose up diff --git a/scripts/db/dml_01.sql b/scripts/db/dml_01.sql index 0ee150a..0d46f89 100644 --- a/scripts/db/dml_01.sql +++ b/scripts/db/dml_01.sql @@ -1 +1 @@ -INSERT INTO users (title,created_on) VALUES('shahzad','2013-06-01'); \ No newline at end of file +INSERT INTO users (title,created_on, uuid) VALUES('shahzad','2013-06-01', '8272-28292-287292'); \ No newline at end of file From e8a2977f196a381794ac6010df10912afd264237 Mon Sep 17 00:00:00 2001 From: Shah Ismail Date: Fri, 11 Sep 2020 17:24:55 +0300 Subject: [PATCH 09/22] More restructuring WIP 3a --- .env | 1 + Makefile | 4 +--- 2 files changed, 2 insertions(+), 3 deletions(-) create mode 100644 .env diff --git a/.env b/.env new file mode 100644 index 0000000..d98cf7f --- /dev/null +++ b/.env @@ -0,0 +1 @@ +COMPOSE_PROJECT_NAME=genitywebapp \ No newline at end of file diff --git a/Makefile b/Makefile index 7651a95..4aaf8b8 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,5 @@ -export NAME=genitywebapp - build: - COMPOSE_PROJECT_NAME=genitywebapp docker-compose up --build + docker-compose build run: build docker-compose up From ba40f0192c9c556a8fb9bfca066d50c800980519 Mon Sep 17 00:00:00 2001 From: Shah Ismail Date: Fri, 11 Sep 2020 18:58:54 +0300 Subject: [PATCH 10/22] More restructuring WIP 3b --- README.md | 2 +- configs/web.env | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index e84423d..eff20ef 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,6 @@ To run docker compose To connect with psql using following command -`docker exec -it poc-golang-postgres-docker_db_1 psql -U root_user -W db_genity` +`docker exec -it genitywebapp_db_1 psql -U root_user -W db_genity` diff --git a/configs/web.env b/configs/web.env index 97b1942..35d07fd 100644 --- a/configs/web.env +++ b/configs/web.env @@ -1,4 +1,4 @@ -dbhost=genityapp_db_1 +dbhost=genitywebapp_db_1 dbport=5432 dbuser=root_user dbpass=shahzad12 From f0f58efe36f7ebf866521c6789275921a3d24ecf Mon Sep 17 00:00:00 2001 From: Shah Ismail Date: Sun, 13 Sep 2020 21:21:54 +0300 Subject: [PATCH 11/22] Code cleanup WIP 4 --- Makefile | 4 +-- cmd/genityapp/main.go | 5 ++- configs/web.env | 2 +- go.mod | 2 +- internal/app/genityapp/api.go | 58 ++++++++++++++++++++++++++--------- 5 files changed, 49 insertions(+), 22 deletions(-) diff --git a/Makefile b/Makefile index 4aaf8b8..85e8e06 100644 --- a/Makefile +++ b/Makefile @@ -5,6 +5,6 @@ run: build docker-compose up build-binary: - GOOS=linux GOARCH=amd64 go build + GOOS=linux GOARCH=amd64 go build -o bins/genityapp -v cmd/genityapp/* -.PHONY: build-binary run build +.PHONY: build-binary run build diff --git a/cmd/genityapp/main.go b/cmd/genityapp/main.go index 8c53afb..22f7c51 100644 --- a/cmd/genityapp/main.go +++ b/cmd/genityapp/main.go @@ -7,7 +7,7 @@ import ( "log" "net/http" - "genityapi" + "domain/genityapp/genityapi" ) var db *sql.DB @@ -32,7 +32,6 @@ func main() { } - func initDb() { config := dbConfig() var err error @@ -54,7 +53,7 @@ func initDb() { func dbConfig() map[string]string { conf := make(map[string]string) - conf[dbhost] = "genitywebapp_db_1" + conf[dbhost] = "genitywebapp_db_1" conf[dbport] = "5432" conf[dbuser] = "root_user" conf[dbpass] = "shahzad12" diff --git a/configs/web.env b/configs/web.env index 35d07fd..e68a234 100644 --- a/configs/web.env +++ b/configs/web.env @@ -1,4 +1,4 @@ -dbhost=genitywebapp_db_1 +dbhost=${COMPOSE_PROJECT_NAME}_db_1 dbport=5432 dbuser=root_user dbpass=shahzad12 diff --git a/go.mod b/go.mod index 45c6723..f3d8b8e 100644 --- a/go.mod +++ b/go.mod @@ -1,4 +1,4 @@ -module genityapi +module domain/genityapp go 1.14 diff --git a/internal/app/genityapp/api.go b/internal/app/genityapp/api.go index 214c42e..789e167 100644 --- a/internal/app/genityapp/api.go +++ b/internal/app/genityapp/api.go @@ -3,6 +3,7 @@ package genityapi import ( "encoding/json" "fmt" + uuid "github.com/nu7hatch/gouuid" "net/http" "time" ) @@ -19,21 +20,38 @@ type Users struct { func UserGetHandler(w http.ResponseWriter, req *http.Request) { if req.Method == "GET" { + + title, ok := req.URL.Query()["title"] + + if !ok || len(title[0]) < 1 { + http.Error(w, "Url Param 'title' is missing", 400) + return + } + + // Query()["key"] will return an array of items, + // we only want the single item. + userTitle := title[0] + users := Users{} - err := queryRepos(&users) + err := queryRepos(&users, userTitle) if err != nil { http.Error(w, err.Error(), 500) return } - out, err := json.Marshal(users.users) - if err != nil { - http.Error(w, err.Error(), 500) - return - } + if len(users.users) > 0 { - fmt.Fprintf(w, string(out)) + out, err := json.Marshal(users.users) + if err != nil { + http.Error(w, err.Error(), 500) + return + } + + fmt.Fprintf(w, string(out)) + } else { + fmt.Fprintf(w, "User does not exist") + } } else { fmt.Fprintf(w, "Sorry, only Get methods are supported for thus api.") } @@ -45,19 +63,26 @@ func UserPostHandler(w http.ResponseWriter, req *http.Request) { fmt.Fprintf(w, "ParseForm() err: %v", err) return } + + uuid, err := uuid.NewV4() + if err != nil { + http.Error(w, err.Error(), 500) + + } + title := req.FormValue("title") sqlInsert := ` -INSERT INTO users (title, created_on) -VALUES ($1, $2) +INSERT INTO users (title, created_on,uuid) +VALUES ($1, $2, $3) RETURNING user_id` if len(title) > 0 { user_id := 0 - row := db.QueryRow(sqlInsert, title, time.Now()) + row := db.QueryRow(sqlInsert, title, time.Now().Format(time.RFC3339), uuid.String()) err := row.Scan(&user_id) if err != nil { panic(err) } - fmt.Fprintf(w, "user creted") + fmt.Fprintf(w, "user created.") } else { fmt.Fprintf(w, "Invalid data") } @@ -66,15 +91,18 @@ RETURNING user_id` } } -func queryRepos(users *Users) error { - rows, err := db.Query(` +func queryRepos(users *Users, userTitle string) error { + query := ` SELECT user_id, title, created_on - FROM users; - `) + FROM users + WHERE title='` + userTitle + `'; + ` + + rows, err := db.Query(query) if err != nil { return err } From 7e9df9b0528c3c1ed660a292963dbbdbc8451b2c Mon Sep 17 00:00:00 2001 From: Shaz hemani Date: Mon, 14 Sep 2020 18:16:47 +0500 Subject: [PATCH 12/22] issue 4, 5 ,6 and 9 fixed --- Dockerfile | 8 ++- cmd/genityapp/main.go | 62 ---------------- cmd/main.go | 22 ++++++ docker-compose.yml | 1 - api.go => internal/app/api.go | 6 +- main.go => internal/app/db.go | 29 +++----- internal/app/genityapp/api.go | 128 ---------------------------------- 7 files changed, 40 insertions(+), 216 deletions(-) delete mode 100644 cmd/genityapp/main.go create mode 100644 cmd/main.go rename api.go => internal/app/api.go (95%) rename main.go => internal/app/db.go (65%) delete mode 100644 internal/app/genityapp/api.go diff --git a/Dockerfile b/Dockerfile index eab6d63..16e4afb 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,8 +1,12 @@ FROM golang:alpine as builder RUN mkdir -p /go/src/app -WORKDIR /go/src/app +WORKDIR /go/src/app/cmd ADD . /go/src/app -RUN go get -d -v \ No newline at end of file +RUN go get -d -v + +Run go build -o bins/genityapp + +CMD ["bins/./genityapp"] \ No newline at end of file diff --git a/cmd/genityapp/main.go b/cmd/genityapp/main.go deleted file mode 100644 index 22f7c51..0000000 --- a/cmd/genityapp/main.go +++ /dev/null @@ -1,62 +0,0 @@ -package main - -import ( - "database/sql" - "fmt" - _ "github.com/lib/pq" - "log" - "net/http" - - "domain/genityapp/genityapi" -) - -var db *sql.DB - -const ( - dbhost = "DBHOST" - dbport = "DBPORT" - dbuser = "DBUSER" - dbpass = "DBPASS" - dbname = "DBNAME" -) - -func main() { - initDb() - defer db.Close() - - http.HandleFunc("/get-data", UserGetHandler) - http.HandleFunc("/post-data", UserPostHandler) - - fmt.Println("Listening on :5000") - log.Fatal(http.ListenAndServe(":5000", nil)) - -} - -func initDb() { - config := dbConfig() - var err error - psqlInfo := fmt.Sprintf("postgres://%v:%v@%v:%v/%v?sslmode=disable", - config[dbuser], config[dbpass], - config[dbhost], config[dbport], config[dbname]) - - fmt.Println(psqlInfo) - db, err = sql.Open("postgres", psqlInfo) - if err != nil { - panic(err) - } - err = db.Ping() - if err != nil { - panic(err) - } - fmt.Println("Successfully connected!") -} - -func dbConfig() map[string]string { - conf := make(map[string]string) - conf[dbhost] = "genitywebapp_db_1" - conf[dbport] = "5432" - conf[dbuser] = "root_user" - conf[dbpass] = "shahzad12" - conf[dbname] = "db_genity" - return conf -} diff --git a/cmd/main.go b/cmd/main.go new file mode 100644 index 0000000..623733f --- /dev/null +++ b/cmd/main.go @@ -0,0 +1,22 @@ +package main + +import ( + "domain/genityapp/internal/app" + "fmt" + _ "github.com/lib/pq" + "log" + "net/http" +) + +func main() { + app.InitDb() + + defer app.CloseDB() + + http.HandleFunc("/get-data", app.UserGetHandler) + http.HandleFunc("/post-data", app.UserPostHandler) + + fmt.Println("Listening on :5000") + log.Fatal(http.ListenAndServe(":5000", nil)) + +} diff --git a/docker-compose.yml b/docker-compose.yml index bab9efc..208fade 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -14,7 +14,6 @@ services: - genity_network web: build: "" - command: [ "go", "run", "main.go","api.go"] env_file: ./configs/web.env ports: - "5000:5000" diff --git a/api.go b/internal/app/api.go similarity index 95% rename from api.go rename to internal/app/api.go index ea57ef3..d5ce527 100644 --- a/api.go +++ b/internal/app/api.go @@ -1,4 +1,4 @@ -package main +package app import ( "encoding/json" @@ -77,7 +77,7 @@ VALUES ($1, $2, $3) RETURNING user_id` if len(title) > 0 { user_id := 0 - row := db.QueryRow(sqlInsert, title, time.Now().Format(time.RFC3339), uuid.String()) + row := Db.QueryRow(sqlInsert, title, time.Now().Format(time.RFC3339), uuid.String()) err := row.Scan(&user_id) if err != nil { panic(err) @@ -102,7 +102,7 @@ func queryRepos(users *Users, userTitle string) error { WHERE title='` + userTitle + `'; ` - rows, err := db.Query(query) + rows, err := Db.Query(query) if err != nil { return err } diff --git a/main.go b/internal/app/db.go similarity index 65% rename from main.go rename to internal/app/db.go index 133d0f4..9cf4753 100644 --- a/main.go +++ b/internal/app/db.go @@ -1,15 +1,10 @@ -package main +package app import ( "database/sql" "fmt" - _ "github.com/lib/pq" - "log" - "net/http" ) -var db *sql.DB - const ( dbhost = "DBHOST" dbport = "DBPORT" @@ -18,19 +13,9 @@ const ( dbname = "DBNAME" ) -func main() { - initDb() - defer db.Close() +var Db *sql.DB - http.HandleFunc("/get-data", UserGetHandler) - http.HandleFunc("/post-data", UserPostHandler) - - fmt.Println("Listening on :5000") - log.Fatal(http.ListenAndServe(":5000", nil)) - -} - -func initDb() { +func InitDb() { config := dbConfig() var err error psqlInfo := fmt.Sprintf("postgres://%v:%v@%v:%v/%v?sslmode=disable", @@ -38,17 +23,21 @@ func initDb() { config[dbhost], config[dbport], config[dbname]) fmt.Println(psqlInfo) - db, err = sql.Open("postgres", psqlInfo) + Db, err = sql.Open("postgres", psqlInfo) if err != nil { panic(err) } - err = db.Ping() + err = Db.Ping() if err != nil { panic(err) } fmt.Println("Successfully connected!") } +func CloseDB() { + Db.Close() +} + func dbConfig() map[string]string { conf := make(map[string]string) conf[dbhost] = "genitywebapp_db_1" diff --git a/internal/app/genityapp/api.go b/internal/app/genityapp/api.go deleted file mode 100644 index 789e167..0000000 --- a/internal/app/genityapp/api.go +++ /dev/null @@ -1,128 +0,0 @@ -package genityapi - -import ( - "encoding/json" - "fmt" - uuid "github.com/nu7hatch/gouuid" - "net/http" - "time" -) - -type User struct { - UserID int - Title string - CreatedOn time.Time -} - -type Users struct { - users []User -} - -func UserGetHandler(w http.ResponseWriter, req *http.Request) { - if req.Method == "GET" { - - title, ok := req.URL.Query()["title"] - - if !ok || len(title[0]) < 1 { - http.Error(w, "Url Param 'title' is missing", 400) - return - } - - // Query()["key"] will return an array of items, - // we only want the single item. - userTitle := title[0] - - users := Users{} - - err := queryRepos(&users, userTitle) - if err != nil { - http.Error(w, err.Error(), 500) - return - } - - if len(users.users) > 0 { - - out, err := json.Marshal(users.users) - if err != nil { - http.Error(w, err.Error(), 500) - return - } - - fmt.Fprintf(w, string(out)) - } else { - fmt.Fprintf(w, "User does not exist") - } - } else { - fmt.Fprintf(w, "Sorry, only Get methods are supported for thus api.") - } -} - -func UserPostHandler(w http.ResponseWriter, req *http.Request) { - if req.Method == "POST" { - if err := req.ParseForm(); err != nil { - fmt.Fprintf(w, "ParseForm() err: %v", err) - return - } - - uuid, err := uuid.NewV4() - if err != nil { - http.Error(w, err.Error(), 500) - - } - - title := req.FormValue("title") - sqlInsert := ` -INSERT INTO users (title, created_on,uuid) -VALUES ($1, $2, $3) -RETURNING user_id` - if len(title) > 0 { - user_id := 0 - row := db.QueryRow(sqlInsert, title, time.Now().Format(time.RFC3339), uuid.String()) - err := row.Scan(&user_id) - if err != nil { - panic(err) - } - fmt.Fprintf(w, "user created.") - } else { - fmt.Fprintf(w, "Invalid data") - } - } else { - fmt.Fprintf(w, "Sorry, only POST methods are supported for thus api.") - } -} - -func queryRepos(users *Users, userTitle string) error { - query := ` - SELECT - user_id, - title, - created_on - - FROM users - WHERE title='` + userTitle + `'; - ` - - rows, err := db.Query(query) - if err != nil { - return err - } - defer rows.Close() - for rows.Next() { - user := User{} - err = rows.Scan( - &user.UserID, - &user.Title, - &user.CreatedOn, - ) - if err != nil { - return err - } - users.users = append(users.users, user) - } - - err = rows.Err() - if err != nil { - return err - } - return nil -} From ede359bcd83c5878803aaf1894c9520538ec5e0d Mon Sep 17 00:00:00 2001 From: Shaz hemani Date: Tue, 15 Sep 2020 12:53:05 +0500 Subject: [PATCH 13/22] Build generation and dockerfile changes --- Dockerfile | 6 +++--- Makefile | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Dockerfile b/Dockerfile index 16e4afb..6e3bbf5 100644 --- a/Dockerfile +++ b/Dockerfile @@ -5,8 +5,8 @@ WORKDIR /go/src/app/cmd ADD . /go/src/app -RUN go get -d -v +#RUN go get -d -v -Run go build -o bins/genityapp +#Run go build -o bins/genityapp -CMD ["bins/./genityapp"] \ No newline at end of file +CMD ["/go/src/app/bins/./genityapp"] \ No newline at end of file diff --git a/Makefile b/Makefile index 85e8e06..2bcdde3 100644 --- a/Makefile +++ b/Makefile @@ -5,6 +5,6 @@ run: build docker-compose up build-binary: - GOOS=linux GOARCH=amd64 go build -o bins/genityapp -v cmd/genityapp/* + GOOS=linux GOARCH=amd64 go build -o bins/genityapp -v cmd/* -.PHONY: build-binary run build +.PHONY: build-binary run build From 1ee48da79f4490f31a1605057d9ae3d375812462 Mon Sep 17 00:00:00 2001 From: Shaz hemani Date: Tue, 15 Sep 2020 14:53:57 +0500 Subject: [PATCH 14/22] Build generation and dockerfile changes --- Makefile | 2 ++ configs/web.env | 2 +- go.mod | 1 + internal/app/db.go | 44 ++++++++++++++++++++++++++++++++++---------- 4 files changed, 38 insertions(+), 11 deletions(-) diff --git a/Makefile b/Makefile index 2bcdde3..2be1aff 100644 --- a/Makefile +++ b/Makefile @@ -7,4 +7,6 @@ run: build build-binary: GOOS=linux GOARCH=amd64 go build -o bins/genityapp -v cmd/* +Dev-run: build-binary build run + .PHONY: build-binary run build diff --git a/configs/web.env b/configs/web.env index e68a234..35d07fd 100644 --- a/configs/web.env +++ b/configs/web.env @@ -1,4 +1,4 @@ -dbhost=${COMPOSE_PROJECT_NAME}_db_1 +dbhost=genitywebapp_db_1 dbport=5432 dbuser=root_user dbpass=shahzad12 diff --git a/go.mod b/go.mod index f3d8b8e..4c7480a 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,7 @@ module domain/genityapp go 1.14 require ( + github.com/joho/godotenv v1.3.0 github.com/lib/pq v1.8.0 github.com/nu7hatch/gouuid v0.0.0-20131221200532-179d4d0c4d8d ) diff --git a/internal/app/db.go b/internal/app/db.go index 9cf4753..13472f9 100644 --- a/internal/app/db.go +++ b/internal/app/db.go @@ -3,14 +3,17 @@ package app import ( "database/sql" "fmt" + "github.com/joho/godotenv" + "log" + "os" ) const ( - dbhost = "DBHOST" - dbport = "DBPORT" - dbuser = "DBUSER" - dbpass = "DBPASS" - dbname = "DBNAME" + dbhost = "dbhost" + dbport = "dbport" + dbuser = "dbuser" + dbpass = "dbpass" + dbname = "dbname" ) var Db *sql.DB @@ -38,12 +41,33 @@ func CloseDB() { Db.Close() } +// return the value of the key +func goDotEnvVariable(key string) string { + + // load .env file + err := godotenv.Load("/go/src/app/configs/web.env") + + if err != nil { + log.Fatalf(err.Error()) + } + + return os.Getenv(key) +} + func dbConfig() map[string]string { + conf := make(map[string]string) - conf[dbhost] = "genitywebapp_db_1" - conf[dbport] = "5432" - conf[dbuser] = "root_user" - conf[dbpass] = "shahzad12" - conf[dbname] = "db_genity" + + user := goDotEnvVariable(dbuser) + host := goDotEnvVariable(dbhost) + port := goDotEnvVariable(dbport) + pass := goDotEnvVariable(dbpass) + databaseNname := goDotEnvVariable(dbname) + + conf[dbhost] = host + conf[dbport] = port + conf[dbuser] = user + conf[dbpass] = pass + conf[dbname] = databaseNname return conf } From e5b366462cf9d19ca16f5fdef532f79ca877a1ca Mon Sep 17 00:00:00 2001 From: Shaz hemani Date: Tue, 15 Sep 2020 16:15:26 +0500 Subject: [PATCH 15/22] relative paths --- Dockerfile | 4 ++-- internal/app/db.go | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/Dockerfile b/Dockerfile index 6e3bbf5..33696ee 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,7 +1,7 @@ FROM golang:alpine as builder RUN mkdir -p /go/src/app -WORKDIR /go/src/app/cmd +WORKDIR /go/src/app ADD . /go/src/app @@ -9,4 +9,4 @@ ADD . /go/src/app #Run go build -o bins/genityapp -CMD ["/go/src/app/bins/./genityapp"] \ No newline at end of file +CMD ["./bins/genityapp"] \ No newline at end of file diff --git a/internal/app/db.go b/internal/app/db.go index 13472f9..1660da6 100644 --- a/internal/app/db.go +++ b/internal/app/db.go @@ -45,7 +45,8 @@ func CloseDB() { func goDotEnvVariable(key string) string { // load .env file - err := godotenv.Load("/go/src/app/configs/web.env") + pwd, _ := os.Getwd() + err := godotenv.Load(pwd + "/configs/web.env") if err != nil { log.Fatalf(err.Error()) From eabffa3cef6fe5cb8ccd964b2156059525f089be Mon Sep 17 00:00:00 2001 From: Shaz hemani Date: Tue, 15 Sep 2020 16:31:48 +0500 Subject: [PATCH 16/22] docker file path in docker compose and cleaning of extra docker file found in project --- Dockerfile | 12 ------------ build/Dockerfile | 3 ++- docker-compose.yml | 4 +++- 3 files changed, 5 insertions(+), 14 deletions(-) delete mode 100644 Dockerfile diff --git a/Dockerfile b/Dockerfile deleted file mode 100644 index 33696ee..0000000 --- a/Dockerfile +++ /dev/null @@ -1,12 +0,0 @@ -FROM golang:alpine as builder - -RUN mkdir -p /go/src/app -WORKDIR /go/src/app - -ADD . /go/src/app - -#RUN go get -d -v - -#Run go build -o bins/genityapp - -CMD ["./bins/genityapp"] \ No newline at end of file diff --git a/build/Dockerfile b/build/Dockerfile index eab6d63..4f52e3d 100644 --- a/build/Dockerfile +++ b/build/Dockerfile @@ -5,4 +5,5 @@ WORKDIR /go/src/app ADD . /go/src/app -RUN go get -d -v \ No newline at end of file + +CMD ["./bins/genityapp"] \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml index 208fade..d7066e3 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -13,7 +13,9 @@ services: networks: - genity_network web: - build: "" + build: + context: . + dockerfile: build/Dockerfile env_file: ./configs/web.env ports: - "5000:5000" From c79b5c4c25a1e1be2a0e2358a2c3664de58f8b98 Mon Sep 17 00:00:00 2001 From: Shah Ismail Date: Tue, 15 Sep 2020 15:10:09 +0300 Subject: [PATCH 17/22] Small changes --- .gitignore | 3 +++ Makefile | 6 +++--- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/.gitignore b/.gitignore index 0328870..3bf1152 100644 --- a/.gitignore +++ b/.gitignore @@ -15,6 +15,9 @@ # Dependency directories (remove the comment below to include it) # vendor/ +# Output directories +bins/ + # ---> macOS # General .DS_Store diff --git a/Makefile b/Makefile index 2be1aff..109eb29 100644 --- a/Makefile +++ b/Makefile @@ -1,12 +1,12 @@ build: docker-compose build -run: build +up: build docker-compose up build-binary: GOOS=linux GOARCH=amd64 go build -o bins/genityapp -v cmd/* -Dev-run: build-binary build run +run: build-binary up -.PHONY: build-binary run build +.PHONY: build-binary run build up From 6f0e9e2462502f1fcd312dd637e6da147f2b50f0 Mon Sep 17 00:00:00 2001 From: Shah Ismail Date: Tue, 15 Sep 2020 15:39:23 +0300 Subject: [PATCH 18/22] WIP5 --- build/Dockerfile | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/build/Dockerfile b/build/Dockerfile index 4f52e3d..16d4795 100644 --- a/build/Dockerfile +++ b/build/Dockerfile @@ -1,9 +1,7 @@ FROM golang:alpine as builder -RUN mkdir -p /go/src/app -WORKDIR /go/src/app +ADD bins/genityapp /etc/local/genityapp -ADD . /go/src/app +WORKDIR /etc/local/ - -CMD ["./bins/genityapp"] \ No newline at end of file +ENTRYPOINT ["./genityapp"] \ No newline at end of file From 69a1fd6070e119209ae6ec4d74fe63dec81e51d2 Mon Sep 17 00:00:00 2001 From: Shaz hemani Date: Tue, 15 Sep 2020 17:59:37 +0500 Subject: [PATCH 19/22] env read from OS env --- go.mod | 1 - internal/app/db.go | 45 ++++++++++++++++++++++----------------------- 2 files changed, 22 insertions(+), 24 deletions(-) diff --git a/go.mod b/go.mod index 4c7480a..f3d8b8e 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,6 @@ module domain/genityapp go 1.14 require ( - github.com/joho/godotenv v1.3.0 github.com/lib/pq v1.8.0 github.com/nu7hatch/gouuid v0.0.0-20131221200532-179d4d0c4d8d ) diff --git a/internal/app/db.go b/internal/app/db.go index 1660da6..f53d291 100644 --- a/internal/app/db.go +++ b/internal/app/db.go @@ -3,8 +3,6 @@ package app import ( "database/sql" "fmt" - "github.com/joho/godotenv" - "log" "os" ) @@ -41,34 +39,35 @@ func CloseDB() { Db.Close() } -// return the value of the key -func goDotEnvVariable(key string) string { - - // load .env file - pwd, _ := os.Getwd() - err := godotenv.Load(pwd + "/configs/web.env") - - if err != nil { - log.Fatalf(err.Error()) - } - - return os.Getenv(key) -} - func dbConfig() map[string]string { conf := make(map[string]string) - user := goDotEnvVariable(dbuser) - host := goDotEnvVariable(dbhost) - port := goDotEnvVariable(dbport) - pass := goDotEnvVariable(dbpass) - databaseNname := goDotEnvVariable(dbname) + host, ok := os.LookupEnv(dbhost) + if !ok { + panic("DBHOST environment variable required but not set") + } + port, ok := os.LookupEnv(dbport) + if !ok { + panic("DBPORT environment variable required but not set") + } + user, ok := os.LookupEnv(dbuser) + if !ok { + panic("DBUSER environment variable required but not set") + } + password, ok := os.LookupEnv(dbpass) + if !ok { + panic("DBPASS environment variable required but not set") + } + name, ok := os.LookupEnv(dbname) + if !ok { + panic("DBNAME environment variable required but not set") + } conf[dbhost] = host conf[dbport] = port conf[dbuser] = user - conf[dbpass] = pass - conf[dbname] = databaseNname + conf[dbpass] = password + conf[dbname] = name return conf } From 0242bce0c05421acd0db52b6bce68910b12b1e6f Mon Sep 17 00:00:00 2001 From: Shaz hemani Date: Tue, 15 Sep 2020 18:27:12 +0500 Subject: [PATCH 20/22] dos2unix test --- Makefile | 1 + build/Dockerfile | 1 + docker-compose.yml | 6 +++--- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/Makefile b/Makefile index 109eb29..2a88db0 100644 --- a/Makefile +++ b/Makefile @@ -9,4 +9,5 @@ build-binary: run: build-binary up + .PHONY: build-binary run build up diff --git a/build/Dockerfile b/build/Dockerfile index 16d4795..e17a0bf 100644 --- a/build/Dockerfile +++ b/build/Dockerfile @@ -1,5 +1,6 @@ FROM golang:alpine as builder + ADD bins/genityapp /etc/local/genityapp WORKDIR /etc/local/ diff --git a/docker-compose.yml b/docker-compose.yml index d7066e3..5431da7 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -11,7 +11,7 @@ services: - "5432" restart: always networks: - - genity_network + - genityapp_network web: build: context: . @@ -25,9 +25,9 @@ services: links: - db networks: - - genity_network + - genityapp_network volumes: db_postgres: networks: - genity_network: + genityapp_network: driver: bridge \ No newline at end of file From 532aa65e3848291e25c45f3ec37407415c1c22d6 Mon Sep 17 00:00:00 2001 From: Shaz hemani Date: Wed, 16 Sep 2020 18:20:22 +0500 Subject: [PATCH 21/22] some refactoring --- README.md | 11 ++++++++++- internal/app/api.go | 38 +++++++++++++++++--------------------- internal/app/db.go | 17 +++++++++++++++++ 3 files changed, 44 insertions(+), 22 deletions(-) diff --git a/README.md b/README.md index eff20ef..f0e4973 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,15 @@ -Just basic golang and postgres docker poc. +#How to run this project + +##Navigate to root of project, run following command +`make run` + +###API interfacing +* Get request + `curl http://localhost:5000/get-data?title=shahzad` +* Post request + `curl --request POST 'http://localhost:5000/post-data' --data "title=shahzad"` To build docker compose `docker-compose up --build` diff --git a/internal/app/api.go b/internal/app/api.go index d5ce527..39d432c 100644 --- a/internal/app/api.go +++ b/internal/app/api.go @@ -12,12 +12,16 @@ type User struct { UserID int Title string CreatedOn time.Time + Uuid string } type Users struct { users []User } +/** +Sample request http://localhost:5000/get-data?title=shahzad +*/ func UserGetHandler(w http.ResponseWriter, req *http.Request) { if req.Method == "GET" { @@ -32,17 +36,17 @@ func UserGetHandler(w http.ResponseWriter, req *http.Request) { // we only want the single item. userTitle := title[0] - users := Users{} + usersData := Users{} - err := queryRepos(&users, userTitle) + err := queryRepos(&usersData, userTitle) if err != nil { http.Error(w, err.Error(), 500) return } - if len(users.users) > 0 { + if len(usersData.users) > 0 { - out, err := json.Marshal(users.users) + out, err := json.Marshal(usersData.users) if err != nil { http.Error(w, err.Error(), 500) return @@ -57,6 +61,9 @@ func UserGetHandler(w http.ResponseWriter, req *http.Request) { } } +/** +Sample request curl --request POST 'http://localhost:5000/post-data' --data "title=shahzad" +*/ func UserPostHandler(w http.ResponseWriter, req *http.Request) { if req.Method == "POST" { if err := req.ParseForm(); err != nil { @@ -71,18 +78,15 @@ func UserPostHandler(w http.ResponseWriter, req *http.Request) { } title := req.FormValue("title") - sqlInsert := ` -INSERT INTO users (title, created_on,uuid) -VALUES ($1, $2, $3) -RETURNING user_id` + if len(title) > 0 { user_id := 0 - row := Db.QueryRow(sqlInsert, title, time.Now().Format(time.RFC3339), uuid.String()) + row := Db.QueryRow(SqlPostUser, title, time.Now().Format(time.RFC3339), uuid.String()) err := row.Scan(&user_id) if err != nil { - panic(err) + fmt.Fprintf(w, err.Error()) } - fmt.Fprintf(w, "user created.") + fmt.Fprintf(w, `title=`+title) } else { fmt.Fprintf(w, "Invalid data") } @@ -92,17 +96,8 @@ RETURNING user_id` } func queryRepos(users *Users, userTitle string) error { - query := ` - SELECT - user_id, - title, - created_on - - FROM users - WHERE title='` + userTitle + `'; - ` - rows, err := Db.Query(query) + rows, err := Db.Query(SqlGetUser, userTitle) if err != nil { return err } @@ -113,6 +108,7 @@ func queryRepos(users *Users, userTitle string) error { &user.UserID, &user.Title, &user.CreatedOn, + &user.Uuid, ) if err != nil { return err diff --git a/internal/app/db.go b/internal/app/db.go index f53d291..5c5aad1 100644 --- a/internal/app/db.go +++ b/internal/app/db.go @@ -14,6 +14,23 @@ const ( dbname = "dbname" ) +const ( + SqlGetUser = ` + SELECT + user_id, + title, + created_on, + uuid + + FROM users + WHERE title=$1; + ` + SqlPostUser = ` +INSERT INTO users (title, created_on,uuid) +VALUES ($1, $2, $3) +RETURNING user_id` +) + var Db *sql.DB func InitDb() { From a41584d9dd0fcaccbcbbdf05add63ea7e6a5bd6f Mon Sep 17 00:00:00 2001 From: Shaz hemani Date: Wed, 16 Sep 2020 18:56:04 +0500 Subject: [PATCH 22/22] target changed --- Makefile | 1 + 1 file changed, 1 insertion(+) diff --git a/Makefile b/Makefile index 2a88db0..8e57b25 100644 --- a/Makefile +++ b/Makefile @@ -5,6 +5,7 @@ up: build docker-compose up build-binary: + go mod download GOOS=linux GOARCH=amd64 go build -o bins/genityapp -v cmd/* run: build-binary up