Esempio n. 1
23
func TestMain(t *testing.T) {

	ctx := context.Background()

	for i, model := range []*simulator.Model{simulator.ESX(), simulator.VPX()} {
		t.Logf("%d", i)
		defer model.Remove()
		err := model.Create()
		if err != nil {
			t.Fatal(err)
		}

		s := model.Service.NewServer()
		defer s.Close()

		s.URL.User = url.UserPassword("user", "pass")
		t.Logf("server URL: %s", s.URL)

		var sess *session.Session
		if i == 0 {
			sess, err = getESXSession(ctx, s.URL.String())
		} else {
			sess, err = getVPXSession(ctx, s.URL.String())
		}
		if err != nil {
			t.Fatal(err)
		}
		defer sess.Logout(ctx)
		testGetChildrenVMs(ctx, sess, t)
		testGetChildVM(ctx, sess, t)
		testFindResourcePool(ctx, sess, t)
		testGetCluster(ctx, sess, t)
	}
}
Esempio n. 2
0
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)
	}
}
Esempio n. 3
0
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
}
Esempio n. 4
0
func TestBasicAuth(t *testing.T) {
	basicAuthTestcase(t, nil, nil)
	basicAuthTestcase(t, nil, url.UserPassword("username", "password"))
	basicAuthTestcase(t, url.UserPassword("usename", "password"), nil)
	basicAuthTestcase(t, url.UserPassword("unused", "unused"),
		url.UserPassword("username", "password"))
}
Esempio n. 5
0
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)
		}
	}
}
Esempio n. 6
0
// Set the API key used for all Get and Push API calls.
func SetAPIKey(apiKey string) {
	pUrl := url.URL{}
	pUrl.Scheme = "https"
	pUrl.User = url.UserPassword(apiKey, "")
	pUrl.Host = "api.pushbullet.com"
	pUrl.Path = "/api/pushes"
	pushUrl = pUrl.String()

	gUrl := url.URL{}
	gUrl.Scheme = "https"
	gUrl.User = url.UserPassword(apiKey, "")
	gUrl.Host = "api.pushbullet.com"
	gUrl.Path = "/api/devices"
	getUrl = gUrl.String()
}
Esempio n. 7
0
// Validate validates the resource.
func (bv *BaseVSphere) Validate() error {
	if err := bv.Base.Validate(); err != nil {
		return err
	}

	if bv.Username == "" {
		return ErrNoUsername
	}

	if bv.Password == "" {
		return ErrNoPassword
	}

	if bv.Endpoint == "" {
		return ErrNoEndpoint
	}

	// Validate the URL to the API endpoint and set the username and password info
	endpoint, err := url.Parse(bv.Endpoint)
	if err != nil {
		return err
	}
	endpoint.User = url.UserPassword(bv.Username, bv.Password)
	bv.url = endpoint

	return nil
}
Esempio n. 8
0
func connectToMessageBus(l logger.Logger, conf *config.Config) yagnats.NATSConn {
	members := make([]string, len(conf.NATS))

	for _, natsConf := range conf.NATS {
		uri := url.URL{
			Scheme: "nats",
			User:   url.UserPassword(natsConf.User, natsConf.Password),
			Host:   fmt.Sprintf("%s:%d", natsConf.Host, natsConf.Port),
		}
		members = append(members, uri.String())
	}

	natsClient, err := yagnats.Connect(members)
	if err != nil {
		l.Error("Failed to connect to the message bus", err)
		os.Exit(1)
	}

	natsClient.AddReconnectedCB(func(conn *nats.Conn) {
		l.Info(fmt.Sprintf("NATS Client Reconnected. Server URL: %s", conn.Opts.Url))
	})

	natsClient.AddClosedCB(func(conn *nats.Conn) {
		err := errors.New(fmt.Sprintf("NATS Client Closed. nats.Conn: %+v", conn))
		l.Error("NATS Closed", err)
		os.Exit(1)
	})

	return natsClient
}
Esempio n. 9
0
File: url.go Progetto: ruflin/beats
// 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)
	}
}
Esempio n. 10
0
func getConfig() (shuttle.Config, error) {
	c, err := parseFlags(shuttle.NewConfig())
	if err != nil {
		return c, err
	}

	if c.MaxAttempts < 1 {
		return c, fmt.Errorf("-max-attempts must be >= 1")
	}

	c.LogsURL = determineLogsURL(os.Getenv("LOGPLEX_URL"), os.Getenv("LOGS_URL"), c.LogsURL)
	oURL, err := validateURL(c.LogsURL)
	if err != nil {
		return c, err
	}

	if oURL.User == nil {
		oURL.User = url.UserPassword("token", c.Appname)
	}

	c.FormatterFunc = determineOutputFormatter(oURL)

	c.LogsURL = oURL.String()

	c.ComputeHeader()

	return c, nil
}
Esempio n. 11
0
// NewVMHost connects to a ESXi or vCenter instance and returns a *VMHost
func NewVMHost(insecure bool, hostURL_param, user, pass string) (*VMHost, error) {
	ctx, _ := context.WithCancel(context.Background())
	hostURL, err := url.Parse("https://" + hostURL_param + "/sdk")
	hostURL.User = url.UserPassword(user, pass)

	cli, err := govmomi.NewClient(ctx, hostURL, insecure)
	if err != nil {
		return nil, err
	}

	mac, err := getLocalMAC()
	if err != nil {
		return nil, err
	}

	vmh := &VMHost{
		client: cli,
		Ctx:    ctx,
		mac:    mac,
	}

	vm, err := vmh.findVM(vmh.mac)
	if err != nil {
		return nil, err
	}
	vmh.Vm = vm

	return vmh, nil
}
Esempio n. 12
0
// Opens a connection to the datasource. See Session().
func (self *Source) Open() error {
	var err error

	connURL := &url.URL{Scheme: "mongodb"}

	if self.config.Port == 0 {
		self.config.Port = 27017
	}

	if self.config.Host == "" {
		self.config.Host = "127.0.0.1"
	}

	connURL.Host = fmt.Sprintf("%s:%d", self.config.Host, self.config.Port)

	if self.config.User != "" {
		connURL.User = url.UserPassword(self.config.User, self.config.Password)
	}

	if self.config.Database != "" {
		connURL.Path = "/" + self.config.Database
	}

	self.session, err = mgo.DialWithTimeout(connURL.String(), 5*time.Second)

	if err != nil {
		return err
	}

	if self.config.Database != "" {
		self.Use(self.config.Database)
	}

	return nil
}
Esempio n. 13
0
func TestClient_BasicAuth(t *testing.T) {
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		u, p, ok := r.BasicAuth()

		if !ok {
			t.Errorf("basic auth error")
		}
		if u != "username" {
			t.Errorf("unexpected username, expected %q, actual %q", "username", u)
		}
		if p != "password" {
			t.Errorf("unexpected password, expected %q, actual %q", "password", p)
		}
		w.WriteHeader(http.StatusNoContent)
	}))
	defer ts.Close()

	u, _ := url.Parse(ts.URL)
	u.User = url.UserPassword("username", "password")
	config := client.Config{URL: *u, Username: "******", Password: "******"}
	c, err := client.NewClient(config)
	if err != nil {
		t.Fatalf("unexpected error.  expected %v, actual %v", nil, err)
	}

	_, _, err = c.Ping()
	if err != nil {
		t.Fatalf("unexpected error.  expected %v, actual %v", nil, err)
	}
}
Esempio n. 14
0
// we'll connect to the database through this function
func Init() {
	dbMutex.Lock()
	defer dbMutex.Unlock()

	if initialized {
		return
	}

	DBUrl = url.URL{
		Scheme:   "postgres",
		Host:     config.Constants.DbAddr,
		Path:     config.Constants.DbDatabase,
		RawQuery: "sslmode=disable",
	}

	logrus.Info("Connecting to DB on %s", DBUrl.String())

	DBUrl.User = url.UserPassword(config.Constants.DbUsername, config.Constants.DbPassword)

	var err error
	DB, err = gorm.Open("postgres", DBUrl.String())
	//	DB, err := gorm.Open("sqlite3", "/tmp/gorm.db")
	if err != nil {
		logrus.Fatal(err.Error())
	}

	DB.SetLogger(logrus.StandardLogger())

	logrus.Info("Connected!")
	initialized = true
}
Esempio n. 15
0
// Update overwrites settings in the target that are derived from the job config
// it belongs to.
func (t *Target) Update(cfg *config.ScrapeConfig, baseLabels, metaLabels clientmodel.LabelSet) {
	t.Lock()
	defer t.Unlock()

	t.url.Scheme = cfg.Scheme
	t.url.Path = string(baseLabels[clientmodel.MetricsPathLabel])
	if cfg.BasicAuth != nil {
		t.url.User = url.UserPassword(cfg.BasicAuth.Username, cfg.BasicAuth.Password)
	}
	t.url.RawQuery = cfg.Params.Encode()

	t.scrapeInterval = time.Duration(cfg.ScrapeInterval)
	t.deadline = time.Duration(cfg.ScrapeTimeout)
	t.httpClient = httputil.NewDeadlineClient(time.Duration(cfg.ScrapeTimeout))

	t.honorLabels = cfg.HonorLabels
	t.metaLabels = metaLabels
	t.baseLabels = clientmodel.LabelSet{}
	// All remaining internal labels will not be part of the label set.
	for name, val := range baseLabels {
		if !strings.HasPrefix(string(name), clientmodel.ReservedLabelPrefix) {
			t.baseLabels[name] = val
		}
	}
	if _, ok := t.baseLabels[clientmodel.InstanceLabel]; !ok {
		t.baseLabels[clientmodel.InstanceLabel] = clientmodel.LabelValue(t.InstanceIdentifier())
	}
	t.metricRelabelConfigs = cfg.MetricRelabelConfigs
}
Esempio n. 16
0
// returns the part after "docker run"
func (conf watchConfig) dockerRunArgs() (args []string) {
	log.Printf("Running watcher with master key %q", masterKey())
	if key := masterKey(); len(key) > 0 {
		tmpKey := "/tmp/watcher.buildkey"
		if _, err := os.Stat(tmpKey); err != nil {
			if err := ioutil.WriteFile(tmpKey, key, 0600); err != nil {
				log.Fatal(err)
			}
		}
		// Images may look for .gobuildkey in / or /root, so provide both.
		// TODO(adg): fix images that look in the wrong place.
		args = append(args, "-v", tmpKey+":/.gobuildkey")
		args = append(args, "-v", tmpKey+":/root/.gobuildkey")
	}
	if conf.netHost {
		args = append(args, "--net=host")
	}
	args = append(args,
		"go-commit-watcher",
		"/usr/local/bin/watcher",
		"-repo="+conf.repo,
		"-dash="+conf.dash,
		"-poll="+conf.interval.String(),
		"-http="+conf.httpAddr,
	)
	if conf.mirrorBase != "" {
		dst, err := url.Parse(conf.mirrorBase)
		if err != nil {
			log.Fatalf("Bad mirror destination URL: %q", conf.mirrorBase)
		}
		dst.User = url.UserPassword(mirrorCred())
		args = append(args, "-mirror="+dst.String())
	}
	return
}
Esempio n. 17
0
func MigratePost(ctx *middleware.Context, form auth.MigrateRepoForm) {
	ctx.Data["Title"] = ctx.Tr("new_migrate")

	ctxUser := checkContextUser(ctx, form.Uid)
	if ctx.Written() {
		return
	}
	ctx.Data["ContextUser"] = ctxUser

	if ctx.HasError() {
		ctx.HTML(200, MIGRATE)
		return
	}

	// Remote address can be HTTP/HTTPS/Git URL or local path.
	// Note: remember to change api/v1/repo.go: MigrateRepo
	// FIXME: merge these two functions with better error handling
	remoteAddr := form.CloneAddr
	if strings.HasPrefix(form.CloneAddr, "http://") ||
		strings.HasPrefix(form.CloneAddr, "https://") ||
		strings.HasPrefix(form.CloneAddr, "git://") {
		u, err := url.Parse(form.CloneAddr)
		if err != nil {
			ctx.Data["Err_CloneAddr"] = true
			ctx.RenderWithErr(ctx.Tr("form.url_error"), MIGRATE, &form)
			return
		}
		if len(form.AuthUsername) > 0 || len(form.AuthPassword) > 0 {
			u.User = url.UserPassword(form.AuthUsername, form.AuthPassword)
		}
		remoteAddr = u.String()
	} else if !com.IsDir(remoteAddr) {
		ctx.Data["Err_CloneAddr"] = true
		ctx.RenderWithErr(ctx.Tr("repo.migrate.invalid_local_path"), MIGRATE, &form)
		return
	}

	repo, err := models.MigrateRepository(ctxUser, form.RepoName, form.Description, form.Private, form.Mirror, remoteAddr)
	if err == nil {
		log.Trace("Repository migrated: %s/%s", ctxUser.Name, form.RepoName)
		ctx.Redirect(setting.AppSubUrl + "/" + ctxUser.Name + "/" + form.RepoName)
		return
	}

	if repo != nil {
		if errDelete := models.DeleteRepository(ctxUser.Id, repo.ID); errDelete != nil {
			log.Error(4, "DeleteRepository: %v", errDelete)
		}
	}

	if strings.Contains(err.Error(), "Authentication failed") ||
		strings.Contains(err.Error(), " not found") ||
		strings.Contains(err.Error(), "could not read Username") {
		ctx.Data["Err_Auth"] = true
		ctx.RenderWithErr(ctx.Tr("form.auth_failed", strings.Replace(err.Error(), ":"+form.AuthPassword+"@", ":<password>@", 1)), MIGRATE, &form)
		return
	}

	handleCreateError(ctx, err, "MigratePost", MIGRATE, &form)
}
Esempio n. 18
0
func TestWorkflowsUnknown(t *testing.T) {
	vro := "https://10.25.37.28:8281/vco/api/workflows/"
	user := "******"
	pass := "******"
	wfname := "unknown"

	tr := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}
	head := &http.Header{}
	head.Set("Accept-Type", "application/json")
	s := napping.Session{
		Client:   &http.Client{Transport: tr},
		Header:   head,
		Userinfo: url.UserPassword(user, pass)}

	np := napping.Params{
		"conditions": fmt.Sprintf("name=%s", wfname)}
	p := np.AsUrlValues()
	j := WorkflowsJSON{}
	r, err := s.Get(vro, &p, &j, nil)
	if err != nil {
		t.Fatal(err)
	}
	if r.Status() != 200 {
		t.Fatal(fmt.Errorf("error calling vRO for %s [%d]", wfname, r.Status()))
	}
	if len(j.Link) != 0 {
		t.Fatal(fmt.Errorf("expect zero vRO %s workflow. Actual %d", wfname, len(j.Link)))
	}

	t.Log("Successfully not found 'unknown'")
}
Esempio n. 19
0
func (c *ShuttleConfig) OutletURL() string {
	var err error
	var oUrl *url.URL

	if len(c.LogsURL) > 0 {
		oUrl, err = url.Parse(c.LogsURL)
		if err != nil {
			log.Fatalf("Unable to parse logs-url")
		}
	}
	if len(LogplexUrl) > 0 {
		oUrl, err = url.Parse(LogplexUrl)
		if err != nil {
			log.Fatalf("Unable to parse $LOGPLEX_URL")
		}
	}

	if oUrl == nil {
		log.Fatalf("Must set -logs-url or $LOGPLEX_URL.")
	}

	if oUrl.User == nil {
		oUrl.User = url.UserPassword("token", c.Appname)
	}
	return oUrl.String()
}
Esempio n. 20
0
// This will process implicit route information received from another server.
// We will check to see if we have configured or are already connected,
// and if so we will ignore. Otherwise we will attempt to connect.
func (s *Server) processImplicitRoute(info *Info) {
	remoteID := info.ID

	s.mu.Lock()
	defer s.mu.Unlock()

	// Don't connect to ourself
	if remoteID == s.info.ID {
		return
	}
	// Check if this route already exists
	if _, exists := s.remotes[remoteID]; exists {
		return
	}
	// Check if we have this route as a configured route
	if s.hasThisRouteConfigured(info) {
		return
	}

	// Initiate the connection, using info.IP instead of info.URL here...
	r, err := url.Parse(info.IP)
	if err != nil {
		Debugf("Error parsing URL from INFO: %v\n", err)
		return
	}
	if info.AuthRequired {
		r.User = url.UserPassword(s.opts.Cluster.Username, s.opts.Cluster.Password)
	}
	s.startGoRoutine(func() { s.connectToRoute(r, false) })
}
Esempio n. 21
0
func applyEnvVariableOverrides() {
	appliedEnvOverrides = make([]string, 0)
	for _, section := range Cfg.Sections() {
		for _, key := range section.Keys() {
			sectionName := strings.ToUpper(strings.Replace(section.Name(), ".", "_", -1))
			keyName := strings.ToUpper(strings.Replace(key.Name(), ".", "_", -1))
			envKey := fmt.Sprintf("GF_%s_%s", sectionName, keyName)
			envValue := os.Getenv(envKey)

			if len(envValue) > 0 {
				key.SetValue(envValue)
				if shouldRedactKey(envKey) {
					envValue = "*********"
				}
				if shouldRedactURLKey(envKey) {
					u, _ := url.Parse(envValue)
					ui := u.User
					if ui != nil {
						_, exists := ui.Password()
						if exists {
							u.User = url.UserPassword(ui.Username(), "-redacted-")
							envValue = u.String()
						}
					}
				}
				appliedEnvOverrides = append(appliedEnvOverrides, fmt.Sprintf("%s=%s", envKey, envValue))
			}
		}
	}
}
Esempio n. 22
0
func (Verifier) Verify(config Config) (authorized bool, err error) {
	blobStoreURL := url.URL{
		Scheme: "http",
		Host:   fmt.Sprintf("%s:%s", config.Host, config.Port),
		User:   url.UserPassword(config.Username, config.Password),
	}

	baseURL := &url.URL{
		Scheme: blobStoreURL.Scheme,
		Host:   blobStoreURL.Host,
		User:   blobStoreURL.User,
		Path:   "/blobs/",
	}

	req, err := http.NewRequest("PROPFIND", baseURL.String(), nil)
	if err != nil {
		return false, err
	}

	req.Header.Add("Depth", "1")
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return false, err
	}

	defer resp.Body.Close()

	return resp.StatusCode == 207, err
}
Esempio n. 23
0
func newOVirtCloud(config io.Reader) (*OVirtCloud, error) {
	if config == nil {
		return nil, fmt.Errorf("missing configuration file for ovirt cloud provider")
	}

	oVirtConfig := OVirtApiConfig{}

	/* defaults */
	oVirtConfig.Connection.Username = "******"

	if err := gcfg.ReadInto(&oVirtConfig, config); err != nil {
		return nil, err
	}

	if oVirtConfig.Connection.ApiEntry == "" {
		return nil, fmt.Errorf("missing ovirt uri in cloud provider configuration")
	}

	request, err := url.Parse(oVirtConfig.Connection.ApiEntry)
	if err != nil {
		return nil, err
	}

	request.Path = path.Join(request.Path, "vms")
	request.User = url.UserPassword(oVirtConfig.Connection.Username, oVirtConfig.Connection.Password)
	request.RawQuery = url.Values{"search": {oVirtConfig.Filters.VmsQuery}}.Encode()

	return &OVirtCloud{VmsRequest: request}, nil
}
Esempio n. 24
0
File: ari.go Progetto: Ulexus/ari
func NewClient(username, password, hostname string, port int, appName string) *Client {
	userinfo := url.UserPassword(username, password)
	endpoint := fmt.Sprintf("http://%s:%d", hostname, port)

	c := &Client{
		hostname: hostname,
		port:     port,
		username: username,
		password: password,
		appName:  appName,
		session: &napping.Session{
			Userinfo: userinfo,
		},
		endpoint: endpoint,
	}
	c.Channels = &ChannelService{client: c}
	c.Bridges = &BridgeService{client: c}
	c.Sounds = &SoundService{client: c}
	c.Playbacks = &PlaybackService{client: c}
	c.Asterisk = &AsteriskService{client: c}
	c.Mailboxes = &MailboxService{client: c}
	c.Recordings = &RecordingService{client: c}
	c.Events = &EventService{client: c}
	c.Applications = &ApplicationService{client: c}
	c.DeviceStates = &DeviceStateService{client: c}
	c.Endpoints = &EndpointService{client: c}

	return c
}
Esempio n. 25
0
// Query sends a command to the server and returns the Results
func (c *Client) Query(q Query) (*Results, error) {
	u := c.url

	u.Path = "query"
	if c.username != "" {
		u.User = url.UserPassword(c.username, c.password)
	}
	values := u.Query()
	values.Set("q", q.Command)
	values.Set("db", q.Database)
	u.RawQuery = values.Encode()

	req, err := http.NewRequest("GET", u.String(), nil)
	if err != nil {
		return nil, err
	}
	req.Header.Set("User-Agent", c.userAgent)
	resp, err := c.httpClient.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	var results Results
	dec := json.NewDecoder(resp.Body)
	dec.UseNumber()
	err = dec.Decode(&results)
	if err != nil {
		return nil, err
	}
	return &results, nil
}
Esempio n. 26
0
// ParseURL is wrapper around url.Parse, where Scheme defaults to "https" and Path defaults to "/sdk"
func ParseURL(s string) (*url.URL, error) {
	var err error
	var u *url.URL

	if s != "" {
		// Default the scheme to https
		if !schemeMatch.MatchString(s) {
			s = "https://" + s
		}

		u, err = url.Parse(s)
		if err != nil {
			return nil, err
		}

		// Default the path to /sdk
		if u.Path == "" {
			u.Path = "/sdk"
		}

		if u.User == nil {
			u.User = url.UserPassword("", "")
		}
	}

	return u, nil
}
Esempio n. 27
0
func (flag *ClientFlag) Set(s string) error {
	var err error

	if s != "" {
		// Default the scheme to https
		if !schemeMatch.MatchString(s) {
			s = "https://" + s
		}

		flag.url, err = url.Parse(s)
		if err != nil {
			return err
		}

		// Default the path to /sdk
		if flag.url.Path == "" {
			flag.url.Path = "/sdk"
		}

		if flag.url.User == nil {
			flag.url.User = url.UserPassword("", "")
		}
	}

	return nil
}
Esempio n. 28
0
func linkArgs(s Service, container string) []string {
	args := []string{}

	prefix := strings.Replace(strings.ToUpper(s.Name), "-", "_", -1)
	env := containerEnv(container)

	scheme := coalesce(env["LINK_SCHEME"], "tcp")
	host := containerHost(container, s.Networks)
	port := containerPort(container)
	path := env["LINK_PATH"]
	username := env["LINK_USERNAME"]
	password := env["LINK_PASSWORD"]

	args = append(args, "--add-host", fmt.Sprintf("%s:%s", s.Name, host))
	args = append(args, "-e", fmt.Sprintf("%s_SCHEME=%s", prefix, scheme))
	args = append(args, "-e", fmt.Sprintf("%s_HOST=%s", prefix, host))
	args = append(args, "-e", fmt.Sprintf("%s_PORT=%s", prefix, port))
	args = append(args, "-e", fmt.Sprintf("%s_PATH=%s", prefix, path))
	args = append(args, "-e", fmt.Sprintf("%s_USERNAME=%s", prefix, username))
	args = append(args, "-e", fmt.Sprintf("%s_PASSWORD=%s", prefix, password))

	u := url.URL{
		Scheme: scheme,
		Host:   fmt.Sprintf("%s:%s", host, port),
		Path:   path,
	}

	if username != "" || password != "" {
		u.User = url.UserPassword(username, password)
	}

	args = append(args, "-e", fmt.Sprintf("%s_URL=%s", prefix, u.String()))

	return args
}
Esempio n. 29
0
func TestClient_BasicAuth(t *testing.T) {
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		u, p, ok := r.BasicAuth()

		if !ok {
			t.Errorf("basic auth error")
		}
		if u != "username" {
			t.Errorf("unexpected username, expected %q, actual %q", "username", u)
		}
		if p != "password" {
			t.Errorf("unexpected password, expected %q, actual %q", "password", p)
		}
		var data Response
		w.WriteHeader(http.StatusOK)
		_ = json.NewEncoder(w).Encode(data)
	}))
	defer ts.Close()

	u, _ := url.Parse(ts.URL)
	u.User = url.UserPassword("username", "password")
	config := Config{URL: u, Username: "******", Password: "******"}
	c := NewClient(config)

	query := Query{}
	_, err := c.Query(query)
	if err != nil {
		t.Fatalf("unexpected error.  expected %v, actual %v", nil, err)
	}
}
Esempio n. 30
0
func NewChimpAPI(apiKey string) *ChimpAPI {
	u := &url.URL{}
	u.Scheme = "https"
	u.Host = fmt.Sprintf("%s.api.mailchimp.com", mailchimp_datacenter.FindString(apiKey))
	u.User = url.UserPassword("", apiKey)
	return &ChimpAPI{url: u}
}