...

Source file src/oras.land/oras-go/examples/simple/simple_push_pull.go

Documentation: oras.land/oras-go/examples/simple

     1  /*
     2  Copyright The ORAS Authors.
     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  
    16  package main
    17  
    18  import (
    19  	"context"
    20  	"fmt"
    21  	"os"
    22  
    23  	"oras.land/oras-go/pkg/content"
    24  	"oras.land/oras-go/pkg/oras"
    25  )
    26  
    27  func check(e error) {
    28  	if e != nil {
    29  		panic(e)
    30  	}
    31  }
    32  
    33  func getLocalRegistryHostname() string {
    34  	hostname := "localhost"
    35  	if v := os.Getenv("LOCAL_REGISTRY_HOSTNAME"); v != "" {
    36  		hostname = v
    37  	}
    38  	return hostname
    39  }
    40  
    41  func main() {
    42  	ref := fmt.Sprintf("%s:5000/oras:test", getLocalRegistryHostname())
    43  	fileName := "hello.txt"
    44  	fileContent := []byte("Hello World!\n")
    45  	customMediaType := "my.custom.media.type"
    46  
    47  	ctx := context.Background()
    48  
    49  	// Push file(s) w custom mediatype to registry
    50  	memoryStore := content.NewMemory()
    51  	desc, err := memoryStore.Add(fileName, customMediaType, fileContent)
    52  	check(err)
    53  
    54  	manifest, manifestDesc, config, configDesc, err := content.GenerateManifestAndConfig(nil, nil, desc)
    55  	check(err)
    56  	memoryStore.Set(configDesc, config)
    57  	err = memoryStore.StoreManifest(ref, manifestDesc, manifest)
    58  	check(err)
    59  	registry, err := content.NewRegistry(content.RegistryOptions{PlainHTTP: true})
    60  	fmt.Printf("Pushing %s to %s...\n", fileName, ref)
    61  	desc, err = oras.Copy(ctx, memoryStore, ref, registry, "")
    62  	check(err)
    63  	fmt.Printf("Pushed to %s with digest %s\n", ref, desc.Digest)
    64  
    65  	// Pull file(s) from registry and save to disk
    66  	fmt.Printf("Pulling from %s and saving to %s...\n", ref, fileName)
    67  	fileStore := content.NewFile("")
    68  	defer fileStore.Close()
    69  	allowedMediaTypes := []string{customMediaType}
    70  	desc, err = oras.Copy(ctx, registry, ref, fileStore, "", oras.WithAllowedMediaTypes(allowedMediaTypes))
    71  	check(err)
    72  	fmt.Printf("Pulled from %s with digest %s\n", ref, desc.Digest)
    73  	fmt.Printf("Try running 'cat %s'\n", fileName)
    74  }
    75  

View as plain text