-
Notifications
You must be signed in to change notification settings - Fork 14
/
main.go
104 lines (88 loc) · 2.25 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
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
101
102
103
104
package main
import (
"log"
"net/http"
"os"
"github.com/cloudfoundry-community/go-cfenv"
"github.com/gin-gonic/gin"
"github.com/joho/godotenv"
)
import "github.com/timjacobi/go-couchdb"
type Visitor struct {
Name string `json:"name"`
}
type Visitors []Visitor
type alldocsResult struct {
TotalRows int `json:"total_rows"`
Offset int
Rows []map[string]interface{}
}
func main() {
r := gin.Default()
r.StaticFile("/", "./static/index.html")
r.Static("/static", "./static")
var dbName = "mydb"
//When running locally, get credentials from .env file.
err := godotenv.Load()
if err != nil {
log.Println(".env file does not exist")
}
cloudantUrl := os.Getenv("CLOUDANT_URL")
appEnv, _ := cfenv.Current()
if appEnv != nil {
cloudantService, _ := appEnv.Services.WithLabel("cloudantNoSQLDB")
if len(cloudantService) > 0 {
cloudantUrl = cloudantService[0].Credentials["url"].(string)
}
}
cloudant, err := couchdb.NewClient(cloudantUrl, nil)
if err != nil {
log.Println("Can not connect to Cloudant database")
}
//ensure db exists
//if the db exists the db will be returned anyway
cloudant.CreateDB(dbName)
/* Endpoint to greet and add a new visitor to database.
* Send a POST request to http://localhost:8080/api/visitors with body
* {
* "name": "Bob"
* }
*/
r.POST("/api/visitors", func(c *gin.Context) {
var visitor Visitor
if c.BindJSON(&visitor) == nil {
cloudant.DB(dbName).Post(visitor)
c.String(200, "Hello "+visitor.Name)
}
})
/**
* Endpoint to get a JSON array of all the visitors in the database
* REST API example:
* <code>
* GET http://localhost:8080/api/visitors
* </code>
*
* Response:
* [ "Bob", "Jane" ]
* @return An array of all the visitor names
*/
r.GET("/api/visitors", func(c *gin.Context) {
var result alldocsResult
if cloudantUrl == "" {
c.JSON(200, gin.H{})
return
}
err := cloudant.DB(dbName).AllDocs(&result, couchdb.Options{"include_docs": true})
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "unable to fetch docs"})
} else {
c.JSON(200, result.Rows)
}
})
//When running on Cloud Foundry, get the PORT from the environment variable.
port := os.Getenv("PORT")
if port == "" {
port = "8080" //Local
}
r.Run(":" + port)
}