github.com/vmware/govmomi@v0.37.2/session/cache/example_test.go (about)

     1  /*
     2  Copyright (c) 2020 VMware, Inc. All Rights Reserved.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package cache_test
    18  
    19  import (
    20  	"context"
    21  	"fmt"
    22  	"net/url"
    23  
    24  	"github.com/vmware/govmomi/session/cache"
    25  	"github.com/vmware/govmomi/simulator"
    26  	"github.com/vmware/govmomi/vim25"
    27  
    28  	"github.com/vmware/govmomi/vapi/rest"
    29  	_ "github.com/vmware/govmomi/vapi/simulator"
    30  )
    31  
    32  func ExampleSession_Login() {
    33  	simulator.Run(func(ctx context.Context, sim *vim25.Client) error {
    34  		u := sim.URL()
    35  		u.User = simulator.DefaultLogin
    36  
    37  		// Login() each client twice
    38  		// 1) creates a new authenticated session
    39  		// 2) uses a cached session (proved by removing the password)
    40  		for i := 0; i < 2; i++ {
    41  			s := &cache.Session{
    42  				URL:      u,
    43  				Insecure: true,
    44  			}
    45  
    46  			vc := new(vim25.Client)
    47  			err := s.Login(ctx, vc, nil)
    48  			if err != nil {
    49  				return err
    50  			}
    51  
    52  			rc := new(rest.Client)
    53  			err = s.Login(ctx, rc, nil)
    54  			if err != nil {
    55  				return err
    56  			}
    57  
    58  			fmt.Printf("%s authenticated\n", u.User)
    59  			u.User = url.User(u.User.Username()) // Remove password
    60  		}
    61  		return nil
    62  	})
    63  	// Output:
    64  	// user:pass authenticated
    65  	// user authenticated
    66  }