go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/gae/example_test.go (about)

     1  // Copyright 2018 The LUCI Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package gae
    16  
    17  import (
    18  	"context"
    19  	"fmt"
    20  	"net/http"
    21  	"net/http/httptest"
    22  
    23  	"go.chromium.org/luci/gae/impl/memory"
    24  	"go.chromium.org/luci/gae/impl/prod"
    25  	"go.chromium.org/luci/gae/service/datastore"
    26  )
    27  
    28  func Example() {
    29  	// This is suitable for use in tests.
    30  	c := memory.Use(context.Background())
    31  	w := httptest.NewRecorder()
    32  	_, err := http.NewRequest("GET", "/doesntmatter", nil)
    33  	if err != nil {
    34  		panic(err)
    35  	}
    36  
    37  	innerHandler(c, w)
    38  	fmt.Printf(string(w.Body.Bytes()))
    39  	// Output: I wrote: dev~app::/CoolStruct,"struct-id"
    40  }
    41  
    42  // This is what you would use in production.
    43  func handler(w http.ResponseWriter, r *http.Request) {
    44  	c := context.Background()
    45  	c = prod.Use(c, r)
    46  	// add production filters, etc. here
    47  	innerHandler(c, w)
    48  }
    49  
    50  type CoolStruct struct {
    51  	ID string `gae:"$id"`
    52  
    53  	Value string
    54  }
    55  
    56  func innerHandler(c context.Context, w http.ResponseWriter) {
    57  	obj := &CoolStruct{ID: "struct-id", Value: "hello"}
    58  	if err := datastore.Put(c, obj); err != nil {
    59  		http.Error(w, err.Error(), http.StatusInternalServerError)
    60  	}
    61  	fmt.Fprintf(w, "I wrote: %s", datastore.KeyForObj(c, obj))
    62  }