post reuqest handled plus some checks

This commit is contained in:
Shaz hemani 2020-09-05 22:33:26 +05:00
parent d176131378
commit 5f593b769a
No known key found for this signature in database
GPG key ID: 976B8B017678D5AC
4 changed files with 49 additions and 18 deletions

View file

@ -10,6 +10,6 @@ To run docker compose
To connect with psql using following command 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`

60
api.go
View file

@ -8,8 +8,8 @@ import (
) )
type User struct { type User struct {
UserID int UserID int
Title string Title string
CreatedOn time.Time CreatedOn time.Time
} }
@ -17,23 +17,53 @@ type Users struct {
users []User users []User
} }
func UserHandler(w http.ResponseWriter, req *http.Request) { func UserGetHandler(w http.ResponseWriter, req *http.Request) {
users := Users{} if req.Method == "GET" {
users := Users{}
err := queryRepos(&users) err := queryRepos(&users)
if err != nil { if err != nil {
http.Error(w, err.Error(), 500) http.Error(w, err.Error(), 500)
return 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) {
out, err := json.Marshal(users.users) if req.Method == "POST" {
if err != nil { if err := req.ParseForm(); err != nil {
http.Error(w, err.Error(), 500) fmt.Fprintf(w, "ParseForm() err: %v", err)
return 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 { func queryRepos(users *Users) error {

View file

@ -1,4 +1,4 @@
CREATE TABLE users ( user_id serial PRIMARY KEY, title VARCHAR ( 50 ) UNIQUE NOT NULL, created_on TIMESTAMP NOT NULL); 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');

View file

@ -22,7 +22,8 @@ func main() {
initDb() initDb()
defer db.Close() defer db.Close()
http.HandleFunc("/api/users", UserHandler) http.HandleFunc("/api/users", UserGetHandler)
http.HandleFunc("/api/user", UserPostHandler)
fmt.Println("Listening on :8080") fmt.Println("Listening on :8080")
log.Fatal(http.ListenAndServe(":8080", nil)) log.Fatal(http.ListenAndServe(":8080", nil))