71 lines
939 B
Go
71 lines
939 B
Go
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 UserHandler(w http.ResponseWriter, req *http.Request) {
|
|
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))
|
|
}
|
|
|
|
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
|
|
}
|