本文整理汇总了Golang中net/url.User函数的典型用法代码示例。如果您正苦于以下问题:Golang User函数的具体用法?Golang User怎么用?Golang User使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了User函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestMakeProxySpec
func TestMakeProxySpec(t *testing.T) {
badTests := [...]url.URL{
{Scheme: "http"},
{Scheme: "http", Host: ":"},
{Scheme: "http", Host: "localhost"},
{Scheme: "http", Host: "localhost:"},
{Scheme: "http", Host: ":8080"},
{Scheme: "http", Host: "localhost:https"},
{Scheme: "http", Host: "localhost:8080", User: url.User("username")},
{Scheme: "http", Host: "localhost:8080", User: url.UserPassword("username", "password")},
{Scheme: "http", User: url.User("username"), Host: "localhost:8080"},
{Scheme: "http", User: url.UserPassword("username", "password"), Host: "localhost:8080"},
{Scheme: "http", Host: "localhost:-1"},
{Scheme: "http", Host: "localhost:65536"},
{Scheme: "socks5", Host: ":"},
{Scheme: "socks4a", Host: ":"},
// "socks" and "socks4" are unknown types.
{Scheme: "socks", Host: "localhost:1080"},
{Scheme: "socks4", Host: "localhost:1080"},
{Scheme: "unknown", Host: "localhost:9999"},
}
goodTests := [...]struct {
input url.URL
expected ProxySpec
}{
{
url.URL{Scheme: "http", Host: "localhost:8080"},
ProxySpec{"http", "localhost", 8080},
},
{
url.URL{Scheme: "socks5", Host: "localhost:1080"},
ProxySpec{"socks5", "localhost", 1080},
},
{
url.URL{Scheme: "socks4a", Host: "localhost:1080"},
ProxySpec{"socks4a", "localhost", 1080},
},
}
for _, input := range badTests {
_, err := makeProxySpec(&input)
if err == nil {
t.Errorf("%q unexpectedly succeeded", input)
}
}
for _, test := range goodTests {
spec, err := makeProxySpec(&test.input)
if err != nil {
t.Fatalf("%q unexpectedly returned an error: %s", test.input, err)
}
if *spec != test.expected {
t.Errorf("%q → %q (expected %q)", test.input, spec, test.expected)
}
}
}
示例2: ToURL
func (config Config) ToURL() *url.URL {
ret := &url.URL{}
hostPort := []string{}
user, pass := "", ""
hasUser, hasPass := false, false
params := &url.Values{}
hasParams := false
for k, v := range config {
var val string
switch t := v.(type) {
case string:
val = t
case interface {
String() string
}:
val = t.String()
case nil:
val = ""
default:
val = fmt.Sprintf("%v", v)
}
switch k {
case "adapter":
ret.Scheme = mappedAdapter(val)
case "host", "hostname":
hostPort = append([]string{val}, hostPort...)
case "port":
hostPort = append(hostPort, val)
case "database":
ret.Path = fmt.Sprintf("/%s", val)
case "user", "username":
user = val
hasUser = true
case "pass", "password":
pass = val
hasPass = true
default:
params.Add(k, val)
hasParams = true
}
}
if len(hostPort) != 0 {
ret.Host = strings.Join(hostPort, ":")
}
if hasPass {
ret.User = url.UserPassword(user, pass)
} else if hasUser {
ret.User = url.User(user)
}
if hasParams {
ret.RawQuery = params.Encode()
}
return ret
}
示例3: openMongo
func openMongo(c *MongoConfig) (b Backend, err error) {
//build a url for connecting based on the config
u := &url.URL{
Scheme: "mongodb",
Host: c.Host,
}
//only add credentials and database in the url if they're specified
if c.Username != "" && c.Password == "" {
u.User = url.User(c.Username)
u.Path = "/" + c.Database
}
if c.Username != "" && c.Password != "" {
u.User = url.UserPassword(c.Username, c.Password)
u.Path = "/" + c.Database
}
s, err := mgo.Dial(u.String())
if err != nil {
err = fmt.Errorf("dial %s: %s", u, err)
return
}
b = &mongoBackend{
tasks: s.DB(c.Database).C("tasks"),
startlog: s.DB(c.Database).C("startlog"),
}
return
}
示例4: makeSQLClient
func makeSQLClient() (*sql.DB, string) {
sqlURL := connURL
if len(connURL) == 0 {
options := url.Values{}
if context.Insecure {
options.Add("sslmode", "disable")
} else {
options.Add("sslmode", "verify-full")
options.Add("sslcert", security.ClientCertPath(context.Certs, connUser))
options.Add("sslkey", security.ClientKeyPath(context.Certs, connUser))
options.Add("sslrootcert", security.CACertPath(context.Certs))
}
pgURL := url.URL{
Scheme: "postgresql",
User: url.User(connUser),
Host: net.JoinHostPort(connHost, connPGPort),
Path: connDBName,
RawQuery: options.Encode(),
}
sqlURL = pgURL.String()
}
db, err := sql.Open("postgres", sqlURL)
if err != nil {
panicf("failed to initialize SQL client: %s", err)
}
return db, sqlURL
}
示例5: processOverride
func processOverride(u *url.URL) {
envUsername := os.Getenv(envUserName)
envPassword := os.Getenv(envPassword)
// Override username if provided
if envUsername != "" {
var password string
var ok bool
if u.User != nil {
password, ok = u.User.Password()
}
if ok {
u.User = url.UserPassword(envUsername, password)
} else {
u.User = url.User(envUsername)
}
}
// Override password if provided
if envPassword != "" {
var username string
if u.User != nil {
username = u.User.Username()
}
u.User = url.UserPassword(username, envPassword)
}
}
示例6: Process
func (flag *ClientFlag) Process() error {
if flag.url == nil {
return errors.New("specify an " + cDescr)
}
// Override username if set
if flag.username != "" {
var password string
var ok bool
if flag.url.User != nil {
password, ok = flag.url.User.Password()
}
if ok {
flag.url.User = url.UserPassword(flag.username, password)
} else {
flag.url.User = url.User(flag.username)
}
}
// Override password if set
if flag.password != "" {
var username string
if flag.url.User != nil {
username = flag.url.User.Username()
}
flag.url.User = url.UserPassword(username, flag.password)
}
return nil
}
示例7: TestPGWireDBName
func TestPGWireDBName(t *testing.T) {
defer leaktest.AfterTest(t)()
s, _, _ := serverutils.StartServer(t, base.TestServerArgs{})
defer s.Stopper().Stop()
pgURL, cleanupFn := sqlutils.PGUrl(t, s.ServingAddr(), "TestPGWireDBName", url.User(security.RootUser))
pgURL.Path = "foo"
defer cleanupFn()
{
db, err := gosql.Open("postgres", pgURL.String())
if err != nil {
t.Fatal(err)
}
defer db.Close()
if _, err := db.Exec(`CREATE DATABASE foo`); err != nil {
t.Fatal(err)
}
if _, err := db.Exec(`CREATE TABLE bar (i INT PRIMARY KEY)`); err != nil {
t.Fatal(err)
}
}
db, err := gosql.Open("postgres", pgURL.String())
if err != nil {
t.Fatal(err)
}
defer db.Close()
if _, err := db.Exec(`INSERT INTO bar VALUES ($1)`, 1); err != nil {
t.Fatal(err)
}
}
示例8: PGUrl
// PGUrl returns a postgres connection url which connects to this server with
// the given user. Returns a connection string and a cleanup function which must
// be called after any connection created using the string has been closed.
//
// In order to connect securely using postgres, this method will create
// temporary on-disk copies of certain embedded security certificates. The
// certificates will be created as temporary files in the provided directory,
// and their filenames will have the provided prefix. The returned cleanup
// function will delete these temporary files.
func PGUrl(t util.Tester, ts *server.TestServer, user, tempDir, prefix string) (url.URL, func()) {
host, port, err := net.SplitHostPort(ts.PGAddr())
if err != nil {
t.Fatal(err)
}
caPath := filepath.Join(security.EmbeddedCertsDir, "ca.crt")
certPath := security.ClientCertPath(security.EmbeddedCertsDir, user)
keyPath := security.ClientKeyPath(security.EmbeddedCertsDir, user)
// Copy these assets to disk from embedded strings, so this test can
// run from a standalone binary.
tempCAPath, tempCACleanup := securitytest.TempRestrictedCopy(t, caPath, tempDir, "TestLogic_ca")
tempCertPath, tempCertCleanup := securitytest.TempRestrictedCopy(t, certPath, tempDir, "TestLogic_cert")
tempKeyPath, tempKeyCleanup := securitytest.TempRestrictedCopy(t, keyPath, tempDir, "TestLogic_key")
return url.URL{
Scheme: "postgres",
User: url.User(user),
Host: net.JoinHostPort(host, port),
RawQuery: fmt.Sprintf("sslmode=verify-full&sslrootcert=%s&sslcert=%s&sslkey=%s",
url.QueryEscape(tempCAPath),
url.QueryEscape(tempCertPath),
url.QueryEscape(tempKeyPath),
),
}, func() {
tempCACleanup()
tempCertCleanup()
tempKeyCleanup()
}
}
示例9: TestEmptyPasswordAuth
func TestEmptyPasswordAuth(t *testing.T) {
defer afterTest(t)
gopher := "gopher"
ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
auth := r.Header.Get("Authorization")
if strings.HasPrefix(auth, "Basic ") {
encoded := auth[6:]
decoded, err := base64.StdEncoding.DecodeString(encoded)
if err != nil {
t.Fatal(err)
}
expected := gopher + ":"
s := string(decoded)
if expected != s {
t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
}
} else {
t.Errorf("Invalid auth %q", auth)
}
}))
defer ts.Close()
c := &Client{}
req, err := NewRequest("GET", ts.URL, nil)
if err != nil {
t.Fatal(err)
}
req.URL.User = url.User(gopher)
resp, err := c.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
}
示例10: sanitizeHTTP
// sanitizeHTTP cleans up repository URL and converts to https format
// if currently in ssh format.
// Returns sanitized url, hostName (e.g. github.com, bitbucket.com)
// and possible error
func sanitizeHTTP(repoURL string) (string, string, error) {
u, err := url.Parse(repoURL)
if err != nil {
return "", "", err
}
// ensure the url is not ssh
if u.Scheme == "ssh" {
u.Scheme = "https"
}
// convert to http format if in ssh format
if strings.Contains(u.Host, ":") {
s := strings.SplitN(u.Host, ":", 2)
// alter path and host if we're sure its not a port
if _, err := strconv.Atoi(s[1]); err != nil {
u.Host = s[0]
u.Path = path.Join(s[1], u.Path)
}
}
// Bitbucket require the user to be set into the HTTP URL
if u.Host == "bitbucket.org" && u.User == nil {
segments := strings.Split(u.Path, "/")
u.User = url.User(segments[1])
}
return u.String(), u.Host, nil
}
示例11: SetURLUser
// SetURLUser set the user credentials in the given URL. If the username or
// password is not set in the URL then the default is used (if provided).
func SetURLUser(u *url.URL, defaultUser, defaultPass string) {
var user, pass string
var userIsSet, passIsSet bool
if u.User != nil {
user = u.User.Username()
if user != "" {
userIsSet = true
}
pass, passIsSet = u.User.Password()
}
if !userIsSet && defaultUser != "" {
userIsSet = true
user = defaultUser
}
if !passIsSet && defaultPass != "" {
passIsSet = true
pass = defaultPass
}
if userIsSet && passIsSet {
u.User = url.UserPassword(user, pass)
} else if userIsSet {
u.User = url.User(user)
}
}
示例12: TestWriteLog
func TestWriteLog(t *testing.T) {
loc, err := time.LoadLocation("Europe/Warsaw")
if err != nil {
panic(err)
}
ts := time.Date(1983, 05, 26, 3, 30, 45, 0, loc)
// A typical request with an OK response
req := newRequest("GET", "http://example.com")
req.RemoteAddr = "192.168.100.5"
buf := new(bytes.Buffer)
writeLog(buf, req, ts, http.StatusOK, 100)
log := buf.String()
expected := "192.168.100.5 - - [26/May/1983:03:30:45 +0200] \"GET HTTP/1.1\" 200 100\n"
if log != expected {
t.Fatalf("wrong log, got %q want %q", log, expected)
}
// Request with an unauthorized user
req.URL.User = url.User("kamil")
buf.Reset()
writeLog(buf, req, ts, http.StatusUnauthorized, 500)
log = buf.String()
expected = "192.168.100.5 - kamil [26/May/1983:03:30:45 +0200] \"GET HTTP/1.1\" 401 500\n"
if log != expected {
t.Fatalf("wrong log, got %q want %q", log, expected)
}
}
示例13: PGURL
// PGURL returns the URL for the postgres endpoint.
func (ctx *Context) PGURL(user string) *url.URL {
// Try to convert path to an absolute path. Failing to do so return path
// unchanged.
absPath := func(path string) string {
r, err := filepath.Abs(path)
if err != nil {
return path
}
return r
}
options := url.Values{}
if ctx.Insecure {
options.Add("sslmode", "disable")
} else {
options.Add("sslmode", "verify-full")
options.Add("sslcert", absPath(ctx.SSLCert))
options.Add("sslkey", absPath(ctx.SSLCertKey))
options.Add("sslrootcert", absPath(ctx.SSLCA))
}
return &url.URL{
Scheme: "postgresql",
User: url.User(user),
Host: ctx.Addr,
RawQuery: options.Encode(),
}
}
示例14: URL
func (c *SSHCmd) URL(path string) *url.URL {
return &url.URL{
User: url.User(c.config.User),
Host: c.host,
Path: path,
}
}
示例15: ParseLocal
// ParseLocal parses rawurl into a URL object with a "file"
// scheme. This will effectively never return an error.
func ParseLocal(rawurl string) (u *url.URL, err error) {
u = new(url.URL)
u.Scheme = "file"
u.User = url.User("")
u.Host = ""
u.Path = rawurl
return u, err
}