Skip to content

Instantly share code, notes, and snippets.

@nkreiger
Created December 28, 2020 19:31
Show Gist options
  • Save nkreiger/cd7f78c351728a69aca8f189cda99de2 to your computer and use it in GitHub Desktop.
Save nkreiger/cd7f78c351728a69aca8f189cda99de2 to your computer and use it in GitHub Desktop.
var ReadCollectionPayload = func(w http.ResponseWriter, r *http.Request) {
(w).Header().Set("Content-Type", "application/json")
var payload mongo.QueryInputs
// Try to decode the request body into the struct. If there is an error,
// respond to the client with the error message and a 400 status code.
err := json.NewDecoder(r.Body).Decode(&payload)
if err != nil {
writeStatus(&w, http.StatusBadRequest, "invalid query payload")
return
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
client, err := mongo.Connect(ctx)
if err != nil {
writeStatus(&w, http.StatusBadRequest, err.Error())
return
}
defer func() {
if err := client.Disconnect(ctx); err != nil {
log.Printf("error disconnecting from client: %v", err)
}
cancel()
}()
executeParams := mongo.ExecuteParams{
Context: ctx,
Database: client.Database("testdb"),
Collection: "testcollection",
}
resp, err := mongo.GetEvents(executeParams, payload)
writeStatus(&w, http.StatusOK, resp)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment