Skip to content

Instantly share code, notes, and snippets.

View nkreiger's full-sized avatar
🏠
Working from home

Noah Kreiger nkreiger

🏠
Working from home
View GitHub Profile
@nkreiger
nkreiger / graceful.go
Created December 29, 2020 17:49
graceful listen and serve
func GracefullyListenAndServe(ctx context.Context, servePort string, rtr *mux.Router) {
http.Handle("/", rtr)
h := &http.Server{
Addr: fmt.Sprintf(":%v", servePort),
Handler: handlers.CORS()(rtr),
}
sig := make(chan os.Signal, 1)
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")
package mongo
import (
"fmt"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo/options"
"log"
)
// GetEvents executes a Find query with query parameters that don't include operations
package mongo
import (
"context"
mgo "go.mongodb.org/mongo-driver/mongo"
)
// ExecuteParams defines the necessary values to execute a
// mongo query
type ExecuteParams struct {
Context context.Context
package mongo
import (
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
)
const (
eventVersionKey = "event.version"
eventTimestampKey = "event.timestamp"
@nkreiger
nkreiger / mongo_health.go
Last active December 29, 2020 17:52
mongo health endpoint
// Connection tests the mongodb connection health
var Health = func(w http.ResponseWriter, r *http.Request) {
(w).Header().Set("Content-Type", "application/json")
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())
// Connect returns a successfully connected mongo client
func Connect(ctx context.Context) (*mongo.Client, error) {
url := "mongodb://admin:admin@localhost:27017"
log.Printf("connect to mongodb at: %v", url)
opts := options.Client()
opts.ApplyURI(url)
@nkreiger
nkreiger / mongo-compose.yaml
Last active December 28, 2020 17:41
basic mongodb setup with express as a GUI
version: '3.7'
services:
mongo:
image: mongo
restart: always
ports:
- 27017:27017
environment:
@nkreiger
nkreiger / health.go
Created December 28, 2020 16:13
general health api endpoint handler
package services
import (
"encoding/json"
"log"
"net/http"
)
type status struct {
Message string `json:"message"`
@nkreiger
nkreiger / gomongo_init_main.go
Last active December 29, 2020 17:49
initial main.go in init branch
func main() {
// create anew http router
rtr := mux.NewRouter()
// health endpoint
rtr.HandleFunc("/health", services.Health).Methods(get)
// use go routinue to serve endpoint
ctx := context.Background()