-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
73 lines (61 loc) · 1.26 KB
/
main.go
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
package main
import (
"database/sql"
"fmt"
"log"
"net/http"
"github.com/gin-gonic/gin"
_ "github.com/lib/pq"
)
type CtfService struct {
Db *sql.DB
}
type Juice struct {
ID int
Name string
}
func (cs *CtfService) Get(c *gin.Context) {
id := c.Param("id")
var juices []Juice
query := fmt.Sprintf("SELECT * FROM juice WHERE id = '%s'", id)
rows, err := cs.Db.Query(query)
if err != nil {
if err == sql.ErrNoRows {
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
} else {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
}
} else {
defer rows.Close()
for rows.Next() {
var juice Juice
err := rows.Scan(&juice.ID, &juice.Name)
if err == nil {
juices = append(juices, juice)
}
}
c.JSON(http.StatusOK, gin.H{"result": juices})
}
}
func initDb() *sql.DB {
connStr := "host=postgresql user=postgres dbname=juice_market sslmode=disable"
db, err := sql.Open("postgres", connStr)
if err != nil {
log.Fatal(err)
}
return db
}
func setupRouter() *gin.Engine {
r := gin.Default()
db := initDb()
service := CtfService{Db: db}
r.GET("/ping", func(c *gin.Context) {
c.String(http.StatusOK, "pong")
})
r.GET("/juice/:id", service.Get)
return r
}
func main() {
r := setupRouter()
r.Run(":8080")
}