diff --git a/README.md b/README.md index 179ea9c..e84423d 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 genity-code-review_db_1 psql -U root_user -W db_genity` +`docker exec -it poc-golang-postgres-docker_db_1 psql -U root_user -W db_genity` diff --git a/api.go b/api.go index 87ff945..4bcc3dc 100644 --- a/api.go +++ b/api.go @@ -8,8 +8,8 @@ import ( ) type User struct { - UserID int - Title string + UserID int + Title string CreatedOn time.Time } @@ -17,23 +17,53 @@ type Users struct { users []User } -func UserHandler(w http.ResponseWriter, req *http.Request) { - users := Users{} +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 + 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.") } +} - - out, err := json.Marshal(users.users) - if err != nil { - http.Error(w, err.Error(), 500) - return +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.") } - - fmt.Fprintf(w, string(out)) } func queryRepos(users *Users) error { diff --git a/db_dump b/db_dump index 9f9dd07..cfacdf5 100644 --- a/db_dump +++ b/db_dump @@ -1,4 +1,4 @@ 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('hemani','2013-06-01'); +INSERT INTO users (title,created_on) VALUES('shahzad','2013-06-01'); diff --git a/main.go b/main.go index 2a03f3a..af6072a 100644 --- a/main.go +++ b/main.go @@ -22,7 +22,8 @@ func main() { initDb() defer db.Close() - http.HandleFunc("/api/users", UserHandler) + http.HandleFunc("/api/users", UserGetHandler) + http.HandleFunc("/api/user", UserPostHandler) fmt.Println("Listening on :8080") log.Fatal(http.ListenAndServe(":8080", nil))