Skip to content

Instantly share code, notes, and snippets.

View wemgl's full-sized avatar

Wembley Leach wemgl

View GitHub Profile
@wemgl
wemgl / main.go
Last active August 31, 2018 18:05
Connecting to a MongoDB Database from Go
// package declaration and imports omitted for brevity
type key string
const (
hostKey = key("hostKey")
usernameKey = key("usernameKey")
passwordKey = key("passwordKey")
databaseKey = key("databaseKey")
)
@wemgl
wemgl / configDB.go
Last active February 23, 2019 12:29
Configuration of the MongoDB Connection
func configDB(ctx context.Context) (*mongo.Database, error) {
uri := fmt.Sprintf(`mongodb://%s:%s@%s/%s`,
ctx.Value(usernameKey).(string),
ctx.Value(passwordKey).(string),
ctx.Value(hostKey).(string),
ctx.Value(databaseKey).(string),
)
client, err := mongo.NewClient(options.Client().ApplyURI(uri))
if err != nil {
return nil, fmt.Errorf("todo: couldn't connect to mongo: %v", err)
res, err := db.Collection(collName).InsertOne(ctx, bson.D{
{"task", t.Task},
{"createdAt", primitive.DateTime(timeMillis(t.CreatedAt))},
{"modifiedAt", primitive.DateTime(timeMillis(t.ModifiedAt))},
})
if err != nil {
return "", fmt.Errorf("createTask: task for to-do list couldn't be created: %v", err)
}
return res.InsertedID.(primitive.ObjectID).Hex(), nil
var t todo
idDoc := bson.D{{"_id", objectIDS}}
err = db.Collection(collName).FindOne(ctx, idDoc).Decode(&t)
if err != nil {
return "", fmt.Errorf("updateTask: couldn't decode task from db: %v", err)
}
var task string
fmt.Println("old task:", t.Task)
fmt.Print("updated task: ")
for input.Scan() {
objectIDS, err := primitive.ObjectIDFromHex(id)
if err != nil {
return 0, fmt.Errorf("deleteTask: couldn't convert to-do ID from input: %v", err)
}
idDoc := bson.D{{"_id", objectIDS}}
res, err := db.Collection(collName).DeleteOne(ctx, idDoc)
if err != nil {
return 0, fmt.Errorf("deleteTask: couldn't delete to-do from db: %v", err)
}
c, err := db.Collection(collName).Find(ctx, bson.D{})
if err != nil {
return fmt.Errorf("readTasks: couldn't list all to-dos: %v", err)
}
defer c.Close(ctx)
tw := tabwriter.NewWriter(os.Stdout, 24, 2, 4, ' ', tabwriter.TabIndent)
_, _ = fmt.Fprintln(tw, "ID\tCreated At\tModified At\tTask\t")
for c.Next(ctx) {
elem := &bson.D{}
if err = c.Decode(elem); err != nil {
@wemgl
wemgl / createSimpleServer.go
Last active March 10, 2019 13:59
main.go for the simple-server medium post
func main() {
mux := http.NewServeMux()
mux.Handle("/public/", logging(public()))
mux.Handle("/", logging(index()))
port, ok := os.LookupEnv("PORT")
if !ok {
port = "8080"
}
@wemgl
wemgl / createSimpleMiddleware.go
Created March 10, 2019 14:00
Example of creating a simple middleware function
// logging is middleware for wrapping any handler we want to track response
// times for and to see what resources are requested.
func logging(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
req := fmt.Sprintf("%s %s", r.Method, r.URL)
log.Println(req)
next.ServeHTTP(w, r)
log.Println(req, "completed in", time.Now().Sub(start))
})
@wemgl
wemgl / createSimpleIndexHandler.go
Last active March 10, 2019 14:29
Example of parsing templates and handling HTTP requests
// templates references the specified templates and caches the parsed results
// to help speed up response times.
var templates = template.Must(template.ParseFiles("./templates/base.html", "./templates/body.html"))
// index is the handler responsible for rending the index page for the site.
func index() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b := struct {
Title template.HTML
BusinessName string
@wemgl
wemgl / createSimpleServerBaseTemplate.html
Created March 10, 2019 14:38
Example of simple HTML templates in Go
{{define "base"}}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="shortcut icon" type="image/x-icon" href="/public/assets/images/favicon.ico">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Work+Sans:400,500,600,700">