POC-golang-postgres-docker/internal/app/api.go

129 lines
2.2 KiB
Go
Raw Normal View History

2020-09-14 13:16:47 +00:00
package app
2020-09-11 09:13:41 +00:00
import (
"encoding/json"
"fmt"
2020-09-11 14:06:41 +00:00
uuid "github.com/nu7hatch/gouuid"
2020-09-11 09:13:41 +00:00
"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" {
2020-09-11 14:06:41 +00:00
title, ok := req.URL.Query()["title"]
if !ok || len(title[0]) < 1 {
http.Error(w, "Url Param 'title' is missing", 400)
2020-09-11 09:13:41 +00:00
return
}
2020-09-11 14:06:41 +00:00
// Query()["key"] will return an array of items,
// we only want the single item.
userTitle := title[0]
users := Users{}
err := queryRepos(&users, userTitle)
2020-09-11 09:13:41 +00:00
if err != nil {
http.Error(w, err.Error(), 500)
return
}
2020-09-11 14:06:41 +00:00
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")
}
2020-09-11 09:13:41 +00:00
} 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
}
2020-09-11 14:06:41 +00:00
uuid, err := uuid.NewV4()
if err != nil {
http.Error(w, err.Error(), 500)
}
2020-09-11 09:13:41 +00:00
title := req.FormValue("title")
sqlInsert := `
2020-09-11 14:06:41 +00:00
INSERT INTO users (title, created_on,uuid)
VALUES ($1, $2, $3)
2020-09-11 09:13:41 +00:00
RETURNING user_id`
if len(title) > 0 {
user_id := 0
2020-09-14 13:16:47 +00:00
row := Db.QueryRow(sqlInsert, title, time.Now().Format(time.RFC3339), uuid.String())
2020-09-11 09:13:41 +00:00
err := row.Scan(&user_id)
if err != nil {
panic(err)
}
2020-09-11 14:06:41 +00:00
fmt.Fprintf(w, "user created.")
2020-09-11 09:13:41 +00:00
} else {
fmt.Fprintf(w, "Invalid data")
}
} else {
fmt.Fprintf(w, "Sorry, only POST methods are supported for thus api.")
}
}
2020-09-11 14:06:41 +00:00
func queryRepos(users *Users, userTitle string) error {
query := `
2020-09-11 09:13:41 +00:00
SELECT
user_id,
title,
created_on
2020-09-11 14:06:41 +00:00
FROM users
WHERE title='` + userTitle + `';
`
2020-09-14 13:16:47 +00:00
rows, err := Db.Query(query)
2020-09-11 09:13:41 +00:00
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
}