Created
September 20, 2021 13:53
-
-
Save crufter/ef55d79eb5596553d0e153cd179cb221 to your computer and use it in GitHub Desktop.
M3o DB api toy increment/decrement toy example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"net/http" | |
"os" | |
m3o "github.com/micro/services/clients/go" | |
db "github.com/micro/services/clients/go/db" | |
) | |
var client = m3o.NewClient(os.Getenv("MICRO_API_TOKEN")) | |
func vote(w http.ResponseWriter, req *http.Request, val float64) { | |
rsp, err := client.DbService.Read(&db.ReadRequest{ | |
Table: "counter", | |
Id: req.URL.Query().Get("id"), | |
}) | |
if err != nil { | |
fmt.Fprintf(w, err.Error()) | |
return | |
} | |
var v float64 | |
if len(rsp.Records) > 0 { | |
rsp.Records[0]["count"] = rsp.Records[0]["count"].(float64) + val | |
v = rsp.Records[0]["count"].(float64) + val | |
_, err = client.DbService.Update(&db.UpdateRequest{ | |
Table: "counter", | |
Id: req.URL.Query().Get("id"), | |
Record: rsp.Records[0], | |
}) | |
if err != nil { | |
fmt.Fprintf(w, err.Error()) | |
return | |
} | |
} else { | |
v = val | |
client.DbService.Create(&db.CreateRequest{ | |
Table: "counter", | |
Record: map[string]interface{}{ | |
"count": val, | |
"id": req.URL.Query().Get("id"), | |
}, | |
}) | |
} | |
fmt.Fprintf(w, fmt.Sprintf("%v", v)) | |
} | |
func upvote(w http.ResponseWriter, req *http.Request) { | |
vote(w, req, 1) | |
} | |
func downvote(w http.ResponseWriter, req *http.Request) { | |
vote(w, req, -1) | |
} | |
func main() { | |
http.HandleFunc("/upvote", upvote) | |
http.HandleFunc("/downvote", downvote) | |
http.ListenAndServe(":8090", nil) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment