POC-golang-postgres-docker/internal/app/api.go
2020-09-16 18:20:22 +05:00

125 lines
2.3 KiB
Go

package app
import (
"encoding/json"
"fmt"
uuid "github.com/nu7hatch/gouuid"
"net/http"
"time"
)
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" {
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]
usersData := Users{}
err := queryRepos(&usersData, userTitle)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
if len(usersData.users) > 0 {
out, err := json.Marshal(usersData.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.")
}
}
/**
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 {
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")
if len(title) > 0 {
user_id := 0
row := Db.QueryRow(SqlPostUser, title, time.Now().Format(time.RFC3339), uuid.String())
err := row.Scan(&user_id)
if err != nil {
fmt.Fprintf(w, err.Error())
}
fmt.Fprintf(w, `title=`+title)
} 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 {
rows, err := Db.Query(SqlGetUser, userTitle)
if err != nil {
return err
}
defer rows.Close()
for rows.Next() {
user := User{}
err = rows.Scan(
&user.UserID,
&user.Title,
&user.CreatedOn,
&user.Uuid,
)
if err != nil {
return err
}
users.users = append(users.users, user)
}
err = rows.Err()
if err != nil {
return err
}
return nil
}