...

Source file src/cloud.google.com/go/cloudsqlconn/instance/conn_name.go

Documentation: cloud.google.com/go/cloudsqlconn/instance

     1  // Copyright 2023 Google LLC
     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  //     https://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 instance
    16  
    17  import (
    18  	"fmt"
    19  	"regexp"
    20  
    21  	"cloud.google.com/go/cloudsqlconn/errtype"
    22  )
    23  
    24  var (
    25  	// Instance connection name is the format <PROJECT>:<REGION>:<INSTANCE>
    26  	// Additionally, we have to support legacy "domain-scoped" projects
    27  	// (e.g. "google.com:PROJECT")
    28  	connNameRegex = regexp.MustCompile("([^:]+(:[^:]+)?):([^:]+):([^:]+)")
    29  )
    30  
    31  // ConnName represents the "instance connection name", in the format
    32  // "project:region:name".
    33  type ConnName struct {
    34  	project string
    35  	region  string
    36  	name    string
    37  }
    38  
    39  func (c *ConnName) String() string {
    40  	return fmt.Sprintf("%s:%s:%s", c.project, c.region, c.name)
    41  }
    42  
    43  // Project returns the project within which the Cloud SQL instance runs.
    44  func (c *ConnName) Project() string {
    45  	return c.project
    46  }
    47  
    48  // Region returns the region where the Cloud SQL instance runs.
    49  func (c *ConnName) Region() string {
    50  	return c.region
    51  }
    52  
    53  // Name returns the Cloud SQL instance name
    54  func (c *ConnName) Name() string {
    55  	return c.name
    56  }
    57  
    58  // ParseConnName initializes a new ConnName struct.
    59  func ParseConnName(cn string) (ConnName, error) {
    60  	b := []byte(cn)
    61  	m := connNameRegex.FindSubmatch(b)
    62  	if m == nil {
    63  		err := errtype.NewConfigError(
    64  			"invalid instance connection name, expected PROJECT:REGION:INSTANCE",
    65  			cn,
    66  		)
    67  		return ConnName{}, err
    68  	}
    69  
    70  	c := ConnName{
    71  		project: string(m[1]),
    72  		region:  string(m[3]),
    73  		name:    string(m[4]),
    74  	}
    75  	return c, nil
    76  }
    77  

View as plain text