Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
100 lines (79 loc) · 2.14 KB
/
Copy pathmain.go
File metadata and controls
100 lines (79 loc) · 2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package main
import (
"database/sql"
"fmt"
"log"
"net/http"
"os"
"github.com/gin-gonic/gin"
_ "github.com/go-sql-driver/mysql"
)
// global Database pointer for handlers to use
var db *sql.DB
type Task struct {
Description string `json:"description"`
CreatedTimestamp string `json:"createdTimestamp"`
}
// TODO: Implement API Error Handling
// type ErrorResponse struct {
// Error string `json:"error"`
// Message string `json:"message"`
// Detail string `json:"detail"`
// }
func getHealth(c *gin.Context) {
err := db.Ping()
if err != nil {
log.Printf("Error pinging MySQL database: %s\n", err.Error())
c.Writer.WriteHeader(http.StatusInternalServerError)
return
}
log.Println("Successful ping")
c.Writer.WriteHeader(http.StatusOK)
}
func getTasks(c *gin.Context) {
log.Println("Attempting query to Task table")
// Query Task Table
rows, err := db.Query("SELECT description, created_timestamp FROM Tasks")
if err != nil {
log.Printf("Error querying Task table: %s\n", err.Error())
c.Writer.WriteHeader(http.StatusInternalServerError)
return
}
defer rows.Close()
var tasks []Task
for rows.Next() {
var task Task
err := rows.Scan(&task.Description, &task.CreatedTimestamp)
if err != nil {
log.Printf("Error converting rows: %s\n", err.Error())
c.Writer.WriteHeader(http.StatusInternalServerError)
return
}
tasks = append(tasks, task)
}
// Return response
c.JSON(http.StatusOK, tasks)
}
func main() {
router := gin.Default()
// Get MYSQL variables
username := os.Getenv("MYSQL_USER")
password := os.Getenv("MYSQL_PASSWORD")
host := os.Getenv("MYSQL_HOST")
port := os.Getenv("MYSQL_PORT")
database := os.Getenv("MYSQL_DATABASE")
log.Println("Attempting to open MySQL connection")
// Establish DB connection.
// Format: USER:PASSWORD@tcp(HOST:PORT)/DATABASE
conn, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s:%s)/%s", username, password, host, port, database))
if err != nil {
log.Fatalf("Error opening MySQL connection: %s", err.Error())
}
db = conn
router.GET("/health", getHealth)
router.GET("/tasks", getTasks)
err = router.Run(":8090")
if err != nil {
log.Fatal(err)
}
}