Utiliser Cloud Storage

Vous pouvez utiliser Cloud Storage pour stocker et diffuser des fichiers, tels que des films, des images ou d'autres contenus statiques.

Ce document explique comment utiliser la bibliothèque cliente Google Cloud dans votre application afin de stocker et de récupérer des données dans Cloud Storage.

Avant de commencer

  • Suivez les instructions de la section "Hello, World!" pour Go sur App Engine pour configurer votre environnement et votre projet, ce qui vous permettra également de comprendre la structure des applications Go dans App Engine. Notez et enregistrez l'ID de votre projet. Vous en aurez besoin pour exécuter l'exemple d'application décrit dans ce document.

  • Veillez à créer un bucket Cloud Storage pour votre application en appelant la commande suivante :

    gsutil mb gs://[YOUR_BUCKET_NAME]
    
  • Rendez le bucket lisible publiquement afin qu'il puisse diffuser des fichiers :

    gsutil defacl set public-read gs://[YOUR_BUCKET_NAME]
    

Télécharger l'exemple

Pour cloner le dépôt, exécutez :

go get -d -v github.com/GoogleCloudPlatform/golang-samples/storage
cd $GOPATH/src/github.com/GoogleCloudPlatform/golang-samples/appengine_flexible/storage

Modifier la configuration du projet et installer les dépendances

Dans app.yaml, définissez GCLOUD_STORAGE_BUCKET. Cette valeur correspond au nom du bucket Cloud Storage que vous avez créé précédemment.

# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

runtime: go
env: flex

automatic_scaling:
  min_num_instances: 1

env_variables:
  GCLOUD_STORAGE_BUCKET: your-bucket-name

Code de l'application

L'exemple d'application présente une page Web invitant l'utilisateur à indiquer un fichier à stocker dans Cloud Storage. Dès que l'utilisateur sélectionne un fichier et clique dessus pour l'envoyer, le gestionnaire d'importation écrit le fichier dans le bucket Cloud Storage à l'aide de la fonction NewWriter de Cloud Storage.

Notez que pour récupérer ce fichier depuis Cloud Storage, vous devez spécifier le nom du bucket et le nom du fichier. Vous devez stocker ces valeurs dans votre application pour une utilisation ultérieure.

// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Sample storage demonstrates use of the cloud.google.com/go/storage package from App Engine flexible environment.
package main

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

	"cloud.google.com/go/storage"
	"google.golang.org/appengine"
)

var (
	storageClient *storage.Client

	// Set this in app.yaml when running in production.
	bucket = os.Getenv("GCLOUD_STORAGE_BUCKET")
)

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

	var err error
	storageClient, err = storage.NewClient(ctx)
	if err != nil {
		log.Fatal(err)
	}

	http.HandleFunc("/", formHandler)
	http.HandleFunc("/upload", uploadHandler)

	appengine.Main()
}

func uploadHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		http.Error(w, "", http.StatusMethodNotAllowed)
		return
	}

	ctx := appengine.NewContext(r)

	f, fh, err := r.FormFile("file")
	if err != nil {
		msg := fmt.Sprintf("Could not get file: %v", err)
		http.Error(w, msg, http.StatusBadRequest)
		return
	}
	defer f.Close()

	sw := storageClient.Bucket(bucket).Object(fh.Filename).NewWriter(ctx)
	if _, err := io.Copy(sw, f); err != nil {
		msg := fmt.Sprintf("Could not write file: %v", err)
		http.Error(w, msg, http.StatusInternalServerError)
		return
	}

	if err := sw.Close(); err != nil {
		msg := fmt.Sprintf("Could not put file: %v", err)
		http.Error(w, msg, http.StatusInternalServerError)
		return
	}

	u, _ := url.Parse("/" + bucket + "/" + sw.Attrs().Name)

	fmt.Fprintf(w, "Successful! URL: https://storage.googleapis.com%s", u.EscapedPath())
}

func formHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprint(w, formHTML)
}

const formHTML = `<!DOCTYPE html>
<html>
  <head>
    <title>Storage</title>
    <meta charset="utf-8">
  </head>
  <body>
    <form method="POST" action="/upload" enctype="multipart/form-data">
      <input type="file" name="file">
      <input type="submit">
    </form>
  </body>
</html>`

Pour en savoir plus

Pour obtenir des informations complètes sur Cloud Storage, consultez la documentation Cloud Storage.