Get hands-on experience with 20+ free Google Cloud products and $300 in free credit for new customers.

Getting Started: App Engine Standard + Go + Datastore

I would like to know the modern (non legacy/depreciated) way to access the datastore from app engine standard standard environment in go.

  • I will maintain this app
  • I'm macOS Swift developer
  • The app will be small and relatively low traffic
  • I would like to do the right things, without having to learn to much

First some code and then some questions. 

 

 

 

package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"os"

	"cloud.google.com/go/datastore"
)

var datastoreClient *datastore.Client

func main() {
	ctx := context.Background()

	var err error
	datastoreClient, err = datastore.NewClient(ctx, "bike-license")

	if err != nil {
		log.Fatal(err)
	}

	http.HandleFunc("/", indexHandler)

	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
		log.Printf("Defaulting to port %s", port)
	}

	log.Printf("Listening on port %s", port)
	if err := http.ListenAndServe(":"+port, nil); err != nil {
		log.Fatal(err)
	}
}

type Entity struct {
	Value string
}

func indexHandler(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path != "/" {
		http.NotFound(w, r)
		return
	}

	ctx := context.Background()
	ctx := r.Context()
	k := datastore.NameKey("Entity", "stringID", nil)
	e := new(Entity)
	if err := datastoreClient.Get(ctx, k, e); err != nil {
		log.Println(err)
	}

	old := e.Value
	e.Value = "Hello World!"

	if _, err := datastoreClient.Put(ctx, k, e); err != nil {
		log.Println(err)
	}

	fmt.Printf("Updated value from %q to %q\n", old, e.Value)
}

 

Update: In above indexHandler I changed from context.Background() to r.Context(). I "think" that makes more sense?

 

This code seems to work. I got it by mashing together some App Engine starter code with some datastore starter code.  I don't fully understand it... in particular if the `ctx` params are right.

I couldn't seem to find any existing examples that do what I want. I found examples that used old depreciated APIs. I also found examples that used App Engine Flex environment. Please point me to any examples I might have missed that use App Engine Standard environment and non-legacy Go API.

  • Is this code correct?
  • How can this code be improved?

Thanks!

0 0 470
0 REPLIES 0