-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler.go
267 lines (223 loc) · 7.19 KB
/
handler.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"os"
"strconv"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos"
)
func helloHandler(w http.ResponseWriter, r *http.Request) {
endpoint := os.Getenv("AZURE_COSMOS_ENDPOINT")
if endpoint == "" {
log.Fatal("AZURE_COSMOS_ENDPOINT could not be found")
}
key := os.Getenv("AZURE_COSMOS_KEY")
if key == "" {
log.Fatal("AZURE_COSMOS_KEY could not be found")
}
var databaseName = "VisitorCounter"
var containerName = "Counter"
// var partitionKey = "/countid"
item := struct {
ID string `json:"id"`
CountId int `json:"countId"`
CreationDate string
}{
ID: "1",
CountId: 0,
CreationDate: "",
}
cred, err := azcosmos.NewKeyCredential(key)
if err != nil {
log.Fatal("Failed to create a credential: ", err)
}
// Create a CosmosDB client
client, err := azcosmos.NewClientWithKey(endpoint, cred, nil)
if err != nil {
log.Fatal("Failed to create cosmos db client: ", err)
}
/*
err = createDatabase(client, databaseName)
if err != nil {
log.Printf("createDatabase failed: %s\n", err)
}
err = createContainer(client, databaseName, containerName, partitionKey)
if err != nil {
log.Printf("createContainer failed: %s\n", err)
}
*/
err = createItem(client, databaseName, containerName, strconv.Itoa(item.CountId), item)
if err != nil {
log.Printf("createItem failed: %s\n", err)
}
err = readItem(client, databaseName, containerName, strconv.Itoa(item.CountId), item.ID)
if err != nil {
log.Printf("readItem failed: %d\n", err)
}
/*
message := "This HTTP triggered function executed successfully. Pass a name in the query string for a personalized response.\n"
name := r.URL.Query().Get("name")
if name != "" {
message = fmt.Sprintf("Hello, %s. This HTTP triggered function executed successfully.\n", name)
}
fmt.Fprint(w, message)
*/
}
func main() {
listenAddr := ":8080"
if val, ok := os.LookupEnv("FUNCTIONS_CUSTOMHANDLER_PORT"); ok {
listenAddr = ":" + val
}
http.HandleFunc("/HttpTrigger", helloHandler)
log.Printf("About to listen on %s. Go to https://127.0.0.1%s/", listenAddr, listenAddr)
log.Fatal(http.ListenAndServe(listenAddr, nil))
}
/*
func createDatabase(client *azcosmos.Client, databaseName string) error {
// databaseName := "adventureworks"
databaseProperties := azcosmos.DatabaseProperties{ID: databaseName}
// This is a helper function that swallows 409 errors
errorIs409 := func(err error) bool {
var responseErr *azcore.ResponseError
return err != nil && errors.As(err, &responseErr) && responseErr.StatusCode == 409
}
ctx := context.TODO()
databaseResp, err := client.CreateDatabase(ctx, databaseProperties, nil)
switch {
case errorIs409(err):
log.Printf("Database [%s] already exists\n", databaseName)
case err != nil:
return err
default:
log.Printf("Database [%v] created. ActivityId %s\n", databaseName, databaseResp.ActivityID)
}
return nil
}
func createContainer(client *azcosmos.Client, databaseName, containerName, partitionKey string) error {
// databaseName = VisitorCounter
// containerName = Counter
// partitionKey = "/countId"
databaseClient, err := client.NewDatabase(databaseName) // returns a struct that represents a database
if err != nil {
log.Fatal("Failed to create a database client:", err)
}
// Setting container properties
containerProperties := azcosmos.ContainerProperties{
ID: containerName,
PartitionKeyDefinition: azcosmos.PartitionKeyDefinition{
Paths: []string{partitionKey},
},
}
// this is a helper function that swallows 409 errors
errorIs409 := func(err error) bool {
var responseErr *azcore.ResponseError
return err != nil && errors.As(err, &responseErr) && responseErr.StatusCode == 409
}
// Setting container options
throughputProperties := azcosmos.NewManualThroughputProperties(400) //defaults to 400 if not set
options := &azcosmos.CreateContainerOptions{
ThroughputProperties: &throughputProperties,
}
ctx := context.TODO()
containerResponse, err := databaseClient.CreateContainer(ctx, containerProperties, options)
if err != nil {
log.Fatal(err)
}
switch {
case errorIs409(err):
log.Printf("Container [%s] already exists\n", containerName)
case err != nil:
return err
default:
log.Printf("Container [%s] created. ActivityId %s\n", containerName, containerResponse.ActivityID)
}
return nil
}
*/
func createItem(client *azcosmos.Client, databaseName, containerName, partitionKey string, item any) error {
// databaseName = VisitorCounter
// containerName = Counter
// partitionKey = "/countId"
/* item = struct {
ID string `json:"id"`
CountId int `json:"countId"`
CreationDate string
}{
ID: "1",
CountId: 0,
CreationDate: "2014-02-25T00:00:00",
}
*/
// create container client
containerClient, err := client.NewContainer(databaseName, containerName)
if err != nil {
return fmt.Errorf("failed to create a container client: %s", err)
}
// specifies the value of the partiton key
pk := azcosmos.NewPartitionKeyString(partitionKey)
b, err := json.Marshal(item)
if err != nil {
return err
}
// setting the item options upon creating ie. consistency level
itemOptions := azcosmos.ItemOptions{
ConsistencyLevel: azcosmos.ConsistencyLevelSession.ToPtr(),
}
// this is a helper function that swallows 409 errors
errorIs409 := func(err error) bool {
var responseErr *azcore.ResponseError
return err != nil && errors.As(err, &responseErr) && responseErr.StatusCode == 409
}
ctx := context.TODO()
itemResponse, err := containerClient.CreateItem(ctx, pk, b, &itemOptions)
switch {
case errorIs409(err):
log.Printf("Item with partitionkey value %s already exists\n", pk)
case err != nil:
return err
default:
log.Printf("Status %d. Item %v created. ActivityId %s. Consuming %v Request Units.\n", itemResponse.RawResponse.StatusCode, pk, itemResponse.ActivityID, itemResponse.RequestCharge)
}
return nil
}
func readItem(client *azcosmos.Client, databaseName, containerName, partitionKey, countId string) error {
// databaseName = VisitorCounter
// containerName = Counter
partitionKey = "/countId"
// countId = "1"
// Create container client
containerClient, err := client.NewContainer(databaseName, containerName)
if err != nil {
return fmt.Errorf("failed to create a container client: %s", err)
}
// Specifies the value of the partiton key
pk := azcosmos.NewPartitionKeyString(partitionKey)
// Read an item
ctx := context.TODO()
itemResponse, err := containerClient.ReadItem(ctx, pk, countId, nil)
if err != nil {
return err
}
itemResponseBody := struct {
ID string `json:"id"`
CountId string `json:"countId"`
CreationDate string
}{}
err = json.Unmarshal(itemResponse.Value, &itemResponseBody)
if err != nil {
return err
}
b, err := json.MarshalIndent(itemResponseBody, "", " ")
if err != nil {
return err
}
fmt.Printf("Read item with customerId %s\n", itemResponseBody.CountId)
fmt.Printf("%s\n", b)
log.Printf("Status %d. Item %v read. ActivityId %s. Consuming %v Request Units.\n", itemResponse.RawResponse.StatusCode, pk, itemResponse.ActivityID, itemResponse.RequestCharge)
return nil
}