POC-golang-postgres-docker/api.go

101 lines
1.7 KiB
Go
Raw Normal View History

2020-09-11 09:13:41 +00:00
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
}