github.com/ydb-platform/ydb-go-sdk/v3@v3.57.0/internal/dsn/dsn.go (about)

     1  package dsn
     2  
     3  import (
     4  	"fmt"
     5  	"net/url"
     6  
     7  	"github.com/ydb-platform/ydb-go-sdk/v3/config"
     8  	"github.com/ydb-platform/ydb-go-sdk/v3/internal/xerrors"
     9  )
    10  
    11  var (
    12  	insecureSchema = "grpc"
    13  	databaseParam  = "database"
    14  )
    15  
    16  type UserInfo struct {
    17  	User     string
    18  	Password string
    19  }
    20  
    21  type parsedInfo struct {
    22  	UserInfo *UserInfo
    23  	Options  []config.Option
    24  	Params   url.Values
    25  }
    26  
    27  func Parse(dsn string) (info parsedInfo, err error) {
    28  	uri, err := url.Parse(dsn)
    29  	if err != nil {
    30  		return info, xerrors.WithStackTrace(err)
    31  	}
    32  	if port := uri.Port(); port == "" {
    33  		return info, xerrors.WithStackTrace(fmt.Errorf("bad connection string '%s': port required", dsn))
    34  	}
    35  	info.Options = append(info.Options,
    36  		config.WithSecure(uri.Scheme != insecureSchema),
    37  		config.WithEndpoint(uri.Host),
    38  		config.WithDatabase(uri.Path),
    39  	)
    40  	if uri.User != nil {
    41  		password, _ := uri.User.Password()
    42  		info.UserInfo = &UserInfo{
    43  			User:     uri.User.Username(),
    44  			Password: password,
    45  		}
    46  	}
    47  	info.Params = uri.Query()
    48  	if database, has := info.Params[databaseParam]; has && len(database) > 0 {
    49  		info.Options = append(info.Options,
    50  			config.WithDatabase(database[0]),
    51  		)
    52  		delete(info.Params, databaseParam)
    53  	}
    54  
    55  	return info, nil
    56  }