-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrdiggerapi.go
108 lines (88 loc) · 2.31 KB
/
rdiggerapi.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
/**
* R Digger Media (https://rdigger.com)
*
*
* @copyright 2019-present R Digger Media <[email protected]>
* 2019-present Appzaib <[email protected]>
* 2019-present Nerdspex <[email protected]>
* 2019-present Rana Jahanzaib <[email protected]>
*
*
*
*
*
*
*
*
* @author Rana Jahanzaib <[email protected]>
*
* @docs https://docs.appzaib.com/rdigger/api
*
* @blueprints https://lab.appzaib.com/org/rdigger/api/blueprints
*
* @package pkg.appzaib.com/rdigger/api
*/
package main
import (
"context"
"encoding/json"
"log"
"net/http"
firebase "firebase.google.com/go"
"github.com/gorilla/mux"
nspx "github.com/nspx/core"
"google.golang.org/appengine"
)
// Init Products var as a slice Product struct
var products []nspx.Product
// Get all Products
func getProducts(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(products)
}
// Get a single Product
func getProduct(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
params := mux.Vars(r) // Get params
// Loop through Products and find with ID
for _, item := range products {
if item.ID == params["id"] {
_ = json.NewEncoder(w).Encode(item)
return
}
}
_ = json.NewEncoder(w).Encode(&nspx.Product{})
}
func main() {
// Init Firestore
// Use the application default credentials
ctx := context.Background()
conf := &firebase.Config{ProjectID: "rdiggerapi"}
app, err := firebase.NewApp(ctx, conf)
if err != nil {
log.Fatalln(err)
}
client, err := app.Firestore(ctx)
if err != nil {
log.Fatalln(err)
}
defer client.Close()
// Store sample data
// _, _, err = client.Collection("users").Add(ctx, map[string]interface{}{
// "first": "Ada",
// "last": "Lovelace",
// "born": 1815,
// })
// if err != nil {
// log.Fatalf("Failed adding alovelace: %v", err)
// }
// Start router
r := mux.NewRouter()
// Sample Data
products = append(products, nspx.Product{ID: "1", Name: "HP 840 G3 Laptop"})
// Endpoints
r.HandleFunc("/products", getProducts).Methods("GET")
r.HandleFunc("/products/{id}", getProduct).Methods("GET")
log.Fatal(http.ListenAndServe(":8080", r))
appengine.Main()
}