예제 #1
0
// NewVAClient returns a new empty client to authenticate against the vCloud Air
// service, the vCloud Air endpoint can be overridden by setting the
// VCLOUDAIR_ENDPOINT environment variable.
func NewVAClient() (*VAClient, error) {

	var u *url.URL
	var err error

	if os.Getenv("VCLOUDAIR_ENDPOINT") != "" {
		u, err = url.ParseRequestURI(os.Getenv("VCLOUDAIR_ENDPOINT"))
		if err != nil {
			return &VAClient{}, fmt.Errorf("cannot parse endpoint coming from VCLOUDAIR_ENDPOINT")
		}
	} else {
		// Implicitly trust this URL parse.
		u, _ = url.ParseRequestURI("https://vchs.vmware.com/api")
	}

	VAClient := VAClient{
		VAEndpoint: *u,
		Client: Client{
			APIVersion: "5.6",
			// Patching things up as we're hitting several TLS timeouts.
			Http: http.Client{
				Transport: &http.Transport{
					Proxy:               http.ProxyFromEnvironment,
					TLSHandshakeTimeout: 120 * time.Second,
				},
			},
		},
	}
	return &VAClient, nil
}
예제 #2
0
// ResolveChartRef resolves a chart reference to a URL.
//
// A reference may be an HTTP URL, a 'reponame/chartname' reference, or a local path.
func (c *ChartDownloader) ResolveChartRef(ref string) (*url.URL, error) {
	// See if it's already a full URL.
	u, err := url.ParseRequestURI(ref)
	if err == nil {
		// If it has a scheme and host and path, it's a full URL
		if u.IsAbs() && len(u.Host) > 0 && len(u.Path) > 0 {
			return u, nil
		}
		return u, fmt.Errorf("Invalid chart url format: %s", ref)
	}

	r, err := repo.LoadRepositoriesFile(c.HelmHome.RepositoryFile())
	if err != nil {
		return u, err
	}

	// See if it's of the form: repo/path_to_chart
	p := strings.Split(ref, "/")
	if len(p) > 1 {
		if baseURL, ok := r.Repositories[p[0]]; ok {
			if !strings.HasSuffix(baseURL, "/") {
				baseURL = baseURL + "/"
			}
			return url.ParseRequestURI(baseURL + strings.Join(p[1:], "/"))
		}
		return u, fmt.Errorf("No such repo: %s", p[0])
	}
	return u, fmt.Errorf("Invalid chart url format: %s", ref)
}
예제 #3
0
func (c *hixie75ServerHandshaker) ReadHandshake(buf *bufio.Reader, req *http.Request) (code int, err error) {
	c.Version = ProtocolVersionHixie75
	if req.Method != "GET" || req.Proto != "HTTP/1.1" {
		return http.StatusMethodNotAllowed, ErrBadRequestMethod
	}
	if req.Header.Get("Upgrade") != "WebSocket" {
		return http.StatusBadRequest, ErrNotWebSocket
	}
	if req.Header.Get("Connection") != "Upgrade" {
		return http.StatusBadRequest, ErrNotWebSocket
	}
	c.Origin, err = url.ParseRequestURI(strings.TrimSpace(req.Header.Get("Origin")))
	if err != nil {
		return http.StatusBadRequest, err
	}

	var scheme string
	if req.TLS != nil {
		scheme = "wss"
	} else {
		scheme = "ws"
	}
	c.Location, err = url.ParseRequestURI(scheme + "://" + req.Host + req.URL.RequestURI())
	if err != nil {
		return http.StatusBadRequest, err
	}
	protocol := strings.TrimSpace(req.Header.Get("Websocket-Protocol"))
	protocols := strings.Split(protocol, ",")
	for i := 0; i < len(protocols); i++ {
		c.Protocol = append(c.Protocol, strings.TrimSpace(protocols[i]))
	}

	return http.StatusSwitchingProtocols, nil
}
예제 #4
0
func TestSocketSameOrigin(t *testing.T) {
	tests := []struct {
		name     string
		origins  [2]string
		expected bool
	}{
		{"Matching domains", [2]string{"https://example.com", "https://example.com"}, true},
		{"Mismatched protocols", [2]string{"http://example.com", "https://example.com"}, false},
		{"Mismatched domains", [2]string{"https://example.com", "https://example.org"}, false},
		{"Mismatched ports", [2]string{"https://example.com:1", "https://example.com:2"}, false},

		// This contradicts RFC 6454, but avoids complicating isSameOrigin with
		// logic for validating and extracting port numbers from hosts.
		// net.SplitHostPort is almost adequate for this, but conflates invalid
		// hosts and missing ports.
		{"Explicit ports", [2]string{"https://example.com", "https://example.com:443"}, false},
	}
	for _, test := range tests {
		a, err := url.ParseRequestURI(test.origins[0])
		if err != nil {
			t.Errorf("On test %s, invalid URL %q: %s", test.name, test.origins[0], err)
		}
		b, err := url.ParseRequestURI(test.origins[1])
		if err != nil {
			t.Errorf("On test %s, invalid URL %q: %s", test.name, test.origins[1], err)
		}
		if actual := isSameOrigin(a, b); actual != test.expected {
			t.Errorf("On test %s, got %s; want %s", test.name, actual, test.expected)
		}
		if actual := isSameOrigin(b, a); actual != test.expected {
			t.Errorf("Test %s not transitive: got %s; want %s", test.name, actual,
				test.expected)
		}
	}
}
예제 #5
0
func TestDropRequestParam(t *testing.T) {

	// Without other params.
	abc := `a.b.c:{"foo":[1,2,3,4]}`
	abcEncoded := url.QueryEscape(abc)

	uri, err := url.ParseRequestURI(fmt.Sprintf(`http://localhost:8181/v1/data/foo/bar?request=%v`, abcEncoded))
	if err != nil {
		panic(err)
	}

	result := dropRequestParam(uri)
	expected := "/v1/data/foo/bar"

	if result != expected {
		t.Errorf("Expected %v but got: %v", expected, result)
	}

	// With other params.
	def := `d.e.f:{"bar":{"baz":null}}`
	defEncoded := url.QueryEscape(def)

	uri, err = url.ParseRequestURI(fmt.Sprintf(`http://localhost:8181/v1/data/foo/bar?request=%v&pretty=true&depth=1&request=%v`, abcEncoded, defEncoded))
	if err != nil {
		panic(err)
	}

	result = dropRequestParam(uri)
	expected = "/v1/data/foo/bar?depth=1&pretty=true"

	if result != expected {
		t.Errorf("Expected %v but got: %v", expected, result)
	}

}
예제 #6
0
func TestClient_vaacquirecompute(t *testing.T) {
	cc := new(callCounter)
	serv := httptest.NewServer(testHandler(map[string]testResponse{
		"/api/vchs/compute/00000000-0000-0000-0000-000000000000": {200, nil, vacompute},
	}, cc))
	// Set up a working client
	os.Setenv("VCLOUDAIR_ENDPOINT", serv.URL+"/api")

	client, err := NewClient()
	if !assert.NoError(t, err) {
		return
	}
	client.VAToken = "012345678901234567890123456789"
	client.Region = "US - Anywhere"

	auc, _ := url.ParseRequestURI(serv.URL + "/api/vchs/compute/00000000-0000-0000-0000-000000000000")
	vavdchref, err := client.vaacquirecompute(auc, "VDC12345-6789")
	if assert.NoError(t, err) && assert.Equal(t, 1, cc.Pop()) {
		assert.Equal(t, serv.URL+"/api/vchs/compute/00000000-0000-0000-0000-000000000000/vdc/00000000-0000-0000-0000-000000000000/vcloudsession", vavdchref.String())
	}

	// Test client errors
	testError := func(param string, resp testResponse) bool {
		serv = httptest.NewServer(testHandler(map[string]testResponse{
			"/api/vchs/compute/00000000-0000-0000-0000-000000000000": resp,
		}, cc))
		os.Setenv("VCLOUDAIR_ENDPOINT", serv.URL+"/api")
		client, err := NewClient()
		if !assert.NoError(t, err) {
			return false
		}
		client.VAToken = "012345678901234567890123456789"
		client.Region = "US - Anywhere"
		auc, _ := url.ParseRequestURI(serv.URL + "/api/vchs/compute/00000000-0000-0000-0000-000000000000")
		_, err = client.vaacquirecompute(auc, param)
		return assert.Error(t, err)
	}

	// Test a 404
	if !testError("VDC12345-6789", testResponse{404, nil, notfoundErr}) {
		return
	}

	// Test an API error
	if !testError("VDC12345-6789", testResponse{500, nil, vcdError}) {
		return
	}

	// Test an unknown VDC ID
	if !testError("INVALID-6789", testResponse{200, nil, vacompute}) {
		return
	}

	// Test an un-parsable response
	if !testError("VDC12345-6789", testResponse{200, nil, notfoundErr}) {
		return
	}

}
예제 #7
0
파일: cp.go 프로젝트: rlmcpherson/s3gof3r
func (cp *cpOpts) Execute(args []string) (err error) {

	k, err := getAWSKeys()
	if err != nil {
		return
	}

	conf := new(s3gof3r.Config)
	*conf = *s3gof3r.DefaultConfig
	s3 := s3gof3r.New(cp.EndPoint, k)
	conf.Concurrency = cp.Concurrency
	if cp.NoSSL {
		conf.Scheme = "http"
	}
	conf.PartSize = cp.PartSize
	conf.Md5Check = !cp.NoMd5
	conf.NTry = cp.NTry
	s3gof3r.SetLogger(os.Stderr, "", log.LstdFlags, cp.Debug)

	src, err := func(src string) (io.ReadCloser, error) {
		if !strings.HasPrefix(strings.ToLower(src), "s3") {
			return os.Open(src)
		}
		u, err := url.ParseRequestURI(src)
		if err != nil {
			return nil, fmt.Errorf("parse error: %s", err)
		}

		r, _, err := s3.Bucket(u.Host).GetReader(u.Path, conf)
		return r, err
	}(cp.Source)
	if err != nil {
		return
	}
	defer checkClose(src, err)

	dst, err := func(dst string) (io.WriteCloser, error) {
		if !strings.HasPrefix(strings.ToLower(dst), "s3") {
			return os.Create(dst)
		}
		u, err := url.ParseRequestURI(dst)
		if err != nil {
			return nil, fmt.Errorf("parse error: %s", err)
		}

		return s3.Bucket(u.Host).PutWriter(u.Path, ACL(cp.Header, cp.ACL), conf)
	}(cp.Dest)
	if err != nil {
		return
	}

	defer checkClose(dst, err)
	_, err = io.Copy(dst, src)
	return
}
예제 #8
0
func TestRoute(t *testing.T) {
	payload1 := []byte("host one")
	s1 := startTestServer(payload1, 0, voidCheck)
	defer s1.Close()

	payload2 := []byte("host two")
	s2 := startTestServer(payload2, 0, voidCheck)
	defer s2.Close()

	doc := fmt.Sprintf(`
		route1: Path("/host-one/*any") -> "%s";
		route2: Path("/host-two/*any") -> "%s"
	`, s1.URL, s2.URL)
	dc, err := testdataclient.NewDoc(doc)
	if err != nil {
		t.Error(err)
	}

	p := New(routing.New(routing.Options{
		nil,
		routing.MatchingOptionsNone,
		sourcePollTimeout,
		[]routing.DataClient{dc},
		nil,
		0}), OptionsNone)

	delay()

	var (
		r *http.Request
		w *httptest.ResponseRecorder
		u *url.URL
	)

	u, _ = url.ParseRequestURI("https://www.example.org/host-one/some/path")
	r = &http.Request{
		URL:    u,
		Method: "GET"}
	w = httptest.NewRecorder()
	p.ServeHTTP(w, r)
	if w.Code != http.StatusOK || !bytes.Equal(w.Body.Bytes(), payload1) {
		t.Error("wrong routing 1")
	}

	u, _ = url.ParseRequestURI("https://www.example.org/host-two/some/path")
	r = &http.Request{
		URL:    u,
		Method: "GET"}
	w = httptest.NewRecorder()
	p.ServeHTTP(w, r)
	if w.Code != http.StatusOK || !bytes.Equal(w.Body.Bytes(), payload2) {
		t.Error("wrong routing 2")
	}
}
예제 #9
0
func (c *hybiServerHandshaker) ReadHandshake(buf *bufio.Reader, req *http.Request) (code int, err error) {
	c.Version = ProtocolVersionHybi13
	if req.Method != "GET" {
		return http.StatusMethodNotAllowed, ErrBadRequestMethod
	}
	// HTTP version can be safely ignored.

	if strings.ToLower(req.Header.Get("Upgrade")) != "websocket" ||
		!strings.Contains(strings.ToLower(req.Header.Get("Connection")), "upgrade") {
		return http.StatusBadRequest, ErrNotWebSocket
	}

	key := req.Header.Get("Sec-Websocket-Key")
	if key == "" {
		return http.StatusBadRequest, ErrChallengeResponse
	}
	version := req.Header.Get("Sec-Websocket-Version")
	var origin string
	switch version {
	case "13":
		c.Version = ProtocolVersionHybi13
		origin = req.Header.Get("Origin")
	case "8":
		c.Version = ProtocolVersionHybi08
		origin = req.Header.Get("Sec-Websocket-Origin")
	default:
		return http.StatusBadRequest, ErrBadWebSocketVersion
	}
	c.Origin, err = url.ParseRequestURI(origin)
	if err != nil {
		return http.StatusForbidden, err
	}
	var scheme string
	if req.TLS != nil {
		scheme = "wss"
	} else {
		scheme = "ws"
	}
	c.Location, err = url.ParseRequestURI(scheme + "://" + req.Host + req.URL.RequestURI())
	if err != nil {
		return http.StatusBadRequest, err
	}
	protocol := strings.TrimSpace(req.Header.Get("Sec-Websocket-Protocol"))
	protocols := strings.Split(protocol, ",")
	for i := 0; i < len(protocols); i++ {
		c.Protocol = append(c.Protocol, strings.TrimSpace(protocols[i]))
	}
	c.accept, err = getNonceAccept([]byte(key))
	if err != nil {
		return http.StatusInternalServerError, err
	}
	return http.StatusSwitchingProtocols, nil
}
예제 #10
0
파일: client.go 프로젝트: Bobberino/musings
// NewConfig creates a new WebSocket config for client connection.
func NewConfig(server, origin string) (config *Config, err error) {
	config = new(Config)
	config.Version = ProtocolVersionHybi13
	config.Location, err = url.ParseRequestURI(server)
	if err != nil {
		return
	}
	config.Origin, err = url.ParseRequestURI(origin)
	if err != nil {
		return
	}
	return
}
예제 #11
0
파일: webhook.go 프로젝트: robinjha/clair
func (h *WebhookNotifier) Configure(config *config.NotifierConfig) (bool, error) {
	// Get configuration
	var httpConfig WebhookNotifierConfiguration
	if config == nil {
		return false, nil
	}
	if _, ok := config.Params["http"]; !ok {
		return false, nil
	}
	yamlConfig, err := yaml.Marshal(config.Params["http"])
	if err != nil {
		return false, errors.New("invalid configuration")
	}
	err = yaml.Unmarshal(yamlConfig, &httpConfig)
	if err != nil {
		return false, errors.New("invalid configuration")
	}

	// Validate endpoint URL.
	if httpConfig.Endpoint == "" {
		return false, nil
	}
	if _, err := url.ParseRequestURI(httpConfig.Endpoint); err != nil {
		return false, fmt.Errorf("could not parse endpoint URL: %s\n", err)
	}
	h.endpoint = httpConfig.Endpoint

	// Setup HTTP client.
	transport := &http.Transport{}
	h.client = &http.Client{
		Transport: transport,
		Timeout:   timeout,
	}

	// Initialize TLS.
	transport.TLSClientConfig, err = loadTLSClientConfig(&httpConfig)
	if err != nil {
		return false, fmt.Errorf("could not initialize client cert auth: %s\n", err)
	}

	// Set proxy.
	if httpConfig.Proxy != "" {
		proxyURL, err := url.ParseRequestURI(httpConfig.Proxy)
		if err != nil {
			return false, fmt.Errorf("could not parse proxy URL: %s\n", err)
		}
		transport.Proxy = http.ProxyURL(proxyURL)
	}

	return true, nil
}
예제 #12
0
func (v *Vdc) FindEdgeGateway(edgegateway string) (EdgeGateway, error) {

	for _, av := range v.Vdc.Link {
		if av.Rel == "edgeGateways" && av.Type == "application/vnd.vmware.vcloud.query.records+xml" {
			u, err := url.ParseRequestURI(av.HREF)

			if err != nil {
				return EdgeGateway{}, fmt.Errorf("error decoding vdc response: %s", err)
			}

			// Querying the Result list
			req := v.c.NewRequest(map[string]string{}, "GET", *u, nil)

			resp, err := checkResp(v.c.Http.Do(req))
			if err != nil {
				return EdgeGateway{}, fmt.Errorf("error retrieving edge gateway records: %s", err)
			}

			query := new(types.QueryResultEdgeGatewayRecordsType)

			if err = decodeBody(resp, query); err != nil {
				return EdgeGateway{}, fmt.Errorf("error decoding edge gateway query response: %s", err)
			}

			u, err = url.ParseRequestURI(query.EdgeGatewayRecord.HREF)
			if err != nil {
				return EdgeGateway{}, fmt.Errorf("error decoding edge gateway query response: %s", err)
			}

			// Querying the Result list
			req = v.c.NewRequest(map[string]string{}, "GET", *u, nil)

			resp, err = checkResp(v.c.Http.Do(req))
			if err != nil {
				return EdgeGateway{}, fmt.Errorf("error retrieving edge gateway: %s", err)
			}

			edge := NewEdgeGateway(v.c)

			if err = decodeBody(resp, edge.EdgeGateway); err != nil {
				return EdgeGateway{}, fmt.Errorf("error decoding edge gateway response: %s", err)
			}

			return *edge, nil

		}
	}
	return EdgeGateway{}, fmt.Errorf("can't find Edge Gateway")

}
예제 #13
0
func TestParseAndDispatchRawData(t *testing.T) {
	url1 := "https://www.zalando.de"
	data := `hello: Path("/hello") -> "https://www.zalando.de"`

	dc := mock.MakeDataClient(data)
	mwr := &mock.FilterRegistry{}
	d := dispatch.Make()
	s := MakeSource(dc, mwr, d)

	c1 := make(chan skipper.Settings)
	c2 := make(chan skipper.Settings)

	s.Subscribe(c1)
	s.Subscribe(c2)

	r, _ := http.NewRequest("GET", "http://localhost:9090/hello", nil)

	// let the settings be populated:
	time.Sleep(3 * time.Millisecond)

	s1 := <-c1
	s2 := <-c2

	rt1, _ := s1.Route(r)
	rt2, _ := s2.Route(r)

	up1, _ := url.ParseRequestURI(url1)
	if rt1.Backend().Scheme() != up1.Scheme || rt1.Backend().Host() != up1.Host ||
		rt2.Backend().Scheme() != up1.Scheme || rt2.Backend().Host() != up1.Host {
		t.Error("wrong url 1")
	}

	data = `hello: Path("/hello") -> "https://www.zalan.do"`
	dc.Feed(data)

	// let the new settings fan through
	time.Sleep(3 * time.Millisecond)

	s1 = <-c1
	s2 = <-c2

	rt1, _ = s1.Route(r)
	rt2, _ = s2.Route(r)
	up2, _ := url.ParseRequestURI("https://www.zalan.do")
	if rt1.Backend().Scheme() != up2.Scheme || rt1.Backend().Host() != up2.Host ||
		rt2.Backend().Scheme() != up2.Scheme || rt2.Backend().Host() != up2.Host {
		t.Error("wrong url 2")
	}
}
예제 #14
0
파일: client.go 프로젝트: fanatic/net
// NewConfig creates a new WebSocket config for client connection.
func NewConfig(server, origin, host string) (config *Config, err error) {
	config = new(Config)
	config.Version = ProtocolVersionHybi13
	config.Location, err = url.ParseRequestURI(server)
	if err != nil {
		return
	}
	config.Origin, err = url.ParseRequestURI(origin)
	if err != nil {
		return
	}
	config.Header = http.Header(make(map[string][]string))
	config.HostOverride = host
	return
}
예제 #15
0
func (s *ServerSuite) TestStartHandleStop() {
	// Start
	taskHandler := func(a *acomm.Request) (interface{}, *url.URL, error) {
		return nil, nil, nil
	}
	s.server.RegisterTask("foobar", taskHandler)

	if !s.NoError(s.server.Start(), "failed to start server") {
		return
	}
	time.Sleep(time.Second)

	// Stop
	defer s.server.Stop()

	// Handle request
	tracker := s.server.Tracker()
	handled := make(chan struct{})
	respHandler := func(req *acomm.Request, resp *acomm.Response) {
		close(handled)
	}
	req, _ := acomm.NewRequest("foobar", tracker.URL().String(), struct{}{}, respHandler, respHandler)
	providerSocket, _ := url.ParseRequestURI("unix://" + s.server.TaskSocketPath("foobar"))
	if !s.NoError(s.server.Tracker().TrackRequest(req, 5*time.Second)) {
		return
	}
	if !s.NoError(acomm.Send(providerSocket, req)) {
		return
	}
	<-handled
}
예제 #16
0
func (v *Vdc) FindVDCNetwork(network string) (OrgVDCNetwork, error) {

	for _, an := range v.Vdc.AvailableNetworks {
		for _, n := range an.Network {
			if n.Name == network {
				u, err := url.ParseRequestURI(n.HREF)
				if err != nil {
					return OrgVDCNetwork{}, fmt.Errorf("error decoding vdc response: %s", err)
				}

				req := v.c.NewRequest(map[string]string{}, "GET", *u, nil)

				resp, err := checkResp(v.c.Http.Do(req))
				if err != nil {
					return OrgVDCNetwork{}, fmt.Errorf("error retreiving orgvdcnetwork: %s", err)
				}

				orgnet := NewOrgVDCNetwork(v.c)

				if err = decodeBody(resp, orgnet.OrgVDCNetwork); err != nil {
					return OrgVDCNetwork{}, fmt.Errorf("error decoding orgvdcnetwork response: %s", err)
				}

				// The request was successful
				return *orgnet, nil

			}
		}
	}

	return OrgVDCNetwork{}, fmt.Errorf("can't find VDC Network: %s", network)
}
예제 #17
0
func (pm prefixMap) registerPrefix(prefix, URI string) error {
	if _, err := url.ParseRequestURI(URI); err != nil {
		return fmt.Errorf("Invalid URI: %s", URI)
	}
	pm[prefix] = URI
	return nil
}
예제 #18
0
// URL constructs a url.URL for use in tests and ensures it's routed by the
// given TestableHandler.
func URL(h TestableHandler, method, rawurl string) *url.URL {
	u, err := url.ParseRequestURI(rawurl)
	if nil != err {
		panic(err)
	}
	if nil != h {
		rq := &http.Request{
			Method: method,
			URL:    u,
		}
		var ok bool
		for {
			h1, _ := h.Handler(rq)
			if _, ok := h1.(tigertonic.NotFoundHandler); ok {
				panic(err)
			}
			if _, ok := h1.(tigertonic.MethodNotAllowedHandler); ok {
				panic(err)
			}
			if h, ok = h1.(TestableHandler); !ok {
				break
			}
		}
	}
	return u
}
예제 #19
0
func (v *Vdc) Refresh() error {

	if v.Vdc.HREF == "" {
		return fmt.Errorf("cannot refresh, Object is empty")
	}

	u, _ := url.ParseRequestURI(v.Vdc.HREF)

	req := v.c.NewRequest(map[string]string{}, "GET", *u, nil)

	resp, err := checkResp(v.c.Http.Do(req))
	if err != nil {
		return fmt.Errorf("error retreiving Edge Gateway: %s", err)
	}

	// Empty struct before a new unmarshal, otherwise we end up with duplicate
	// elements in slices.
	v.Vdc = &types.Vdc{}

	if err = decodeBody(resp, v.Vdc); err != nil {
		return fmt.Errorf("error decoding Edge Gateway response: %s", err)
	}

	// The request was successful
	return nil
}
예제 #20
0
파일: api_test.go 프로젝트: cdosso/machine
func TestClient_NewRequest(t *testing.T) {
	c := makeClient(t)

	params := map[string]string{
		"foo": "bar",
		"baz": "bar",
	}

	uri, _ := url.ParseRequestURI("http://localhost:4444/api/bar")

	req := c.NewRequest(params, "POST", *uri, nil)

	encoded := req.URL.Query()
	if encoded.Get("foo") != "bar" {
		t.Fatalf("bad: %v", encoded)
	}

	if encoded.Get("baz") != "bar" {
		t.Fatalf("bad: %v", encoded)
	}

	if req.URL.String() != "http://localhost:4444/api/bar?baz=bar&foo=bar" {
		t.Fatalf("bad base url: %v", req.URL.String())
	}

	if req.Header.Get("x-vcloud-authorization") != "01234567890123456789012345678901" {
		t.Fatalf("bad auth header: %v", req.Header)
	}

	if req.Method != "POST" {
		t.Fatalf("bad method: %v", req.Method)
	}

}
예제 #21
0
// Doesn't work with vCloud API 5.5, only vCloud Air
func (v *Vdc) GetVDCOrg() (Org, error) {

	for _, av := range v.Vdc.Link {
		if av.Rel == "up" && av.Type == "application/vnd.vmware.vcloud.org+xml" {
			u, err := url.ParseRequestURI(av.HREF)

			if err != nil {
				return Org{}, fmt.Errorf("error decoding vdc response: %s", err)
			}

			req := v.c.NewRequest(map[string]string{}, "GET", *u, nil)

			resp, err := checkResp(v.c.Http.Do(req))
			if err != nil {
				return Org{}, fmt.Errorf("error retreiving org: %s", err)
			}

			org := NewOrg(v.c)

			if err = decodeBody(resp, org.Org); err != nil {
				return Org{}, fmt.Errorf("error decoding org response: %s", err)
			}

			// The request was successful
			return *org, nil

		}
	}
	return Org{}, fmt.Errorf("can't find VDC Org")
}
예제 #22
0
func TestMailChimpGatherError(t *testing.T) {
	ts := httptest.NewServer(
		http.HandlerFunc(
			func(w http.ResponseWriter, r *http.Request) {
				w.WriteHeader(http.StatusOK)
				fmt.Fprintln(w, sampleError)
			},
		))
	defer ts.Close()

	u, err := url.ParseRequestURI(ts.URL)
	require.NoError(t, err)

	api := &ChimpAPI{
		url:   u,
		Debug: true,
	}
	m := MailChimp{
		api:        api,
		CampaignId: "test",
	}

	var acc testutil.Accumulator
	err = m.Gather(&acc)
	require.Error(t, err)
}
예제 #23
0
func TestTokenDisassociate(t *testing.T) {
	var request http.Request = http.Request{}
	request.URL, _ = url.ParseRequestURI("http://www.syncmysport.com/token/12345")

	TokenDisassociate(responseWriter, &request)

}
예제 #24
0
파일: validation.go 프로젝트: intfrr/goa
func (a *APIDefinition) validateLicense(verr *dslengine.ValidationErrors) {
	if a.License != nil && a.License.URL != "" {
		if _, err := url.ParseRequestURI(a.License.URL); err != nil {
			verr.Add(a, "invalid license URL value: %s", err)
		}
	}
}
예제 #25
0
파일: validation.go 프로젝트: intfrr/goa
func (a *APIDefinition) validateDocs(verr *dslengine.ValidationErrors) {
	if a.Docs != nil && a.Docs.URL != "" {
		if _, err := url.ParseRequestURI(a.Docs.URL); err != nil {
			verr.Add(a, "invalid docs URL value: %s", err)
		}
	}
}
예제 #26
0
파일: validation.go 프로젝트: intfrr/goa
func (a *APIDefinition) validateContact(verr *dslengine.ValidationErrors) {
	if a.Contact != nil && a.Contact.URL != "" {
		if _, err := url.ParseRequestURI(a.Contact.URL); err != nil {
			verr.Add(a, "invalid contact URL value: %s", err)
		}
	}
}
예제 #27
0
func doJsonEncodedPost(payload map[string]interface{}) (*http.Response, error) {
	payloadBytes, err := json.Marshal(payload)
	if err != nil {
		return nil, err
	}

	u, err := url.ParseRequestURI(test_server.URL())
	if err != nil {
		return nil, err
	}

	u.Path = "/"
	urlStr := fmt.Sprintf("%v", u)
	req, err := http.NewRequest("POST", urlStr, bytes.NewBuffer(payloadBytes))
	if err != nil {
		return nil, err
	}

	req.Header.Add("Content-Type", "application/json")
	client := &http.Client{}
	res, err := client.Do(req)
	if err != nil {
		return nil, err
	}

	return res, nil
}
예제 #28
0
// PlatformAdd build and push a new docker platform to register
func (p *dockerProvisioner) PlatformAdd(name string, args map[string]string, w io.Writer) error {
	if args["dockerfile"] == "" {
		return errors.New("Dockerfile is required.")
	}
	if _, err := url.ParseRequestURI(args["dockerfile"]); err != nil {
		return errors.New("dockerfile parameter should be an url.")
	}
	imageName := platformImageName(name)
	cluster := p.Cluster()
	buildOptions := docker.BuildImageOptions{
		Name:           imageName,
		NoCache:        true,
		RmTmpContainer: true,
		Remote:         args["dockerfile"],
		InputStream:    nil,
		OutputStream:   w,
	}
	err := cluster.BuildImage(buildOptions)
	if err != nil {
		return err
	}
	parts := strings.Split(imageName, ":")
	var tag string
	if len(parts) > 2 {
		imageName = strings.Join(parts[:len(parts)-1], ":")
		tag = parts[len(parts)-1]
	} else if len(parts) > 1 {
		imageName = parts[0]
		tag = parts[1]
	} else {
		imageName = parts[0]
		tag = "latest"
	}
	return p.PushImage(imageName, tag)
}
예제 #29
0
파일: rm.go 프로젝트: elblivion/s3gof3r
func (rm *rmOpts) Execute(args []string) error {

	k, err := getAWSKeys()
	if err != nil {
		return err
	}

	conf := new(s3gof3r.Config)
	*conf = *s3gof3r.DefaultConfig
	s3 := s3gof3r.New(rm.EndPoint, k)
	s3gof3r.SetLogger(os.Stderr, "", log.Ltime, rm.Debug)

	// parse positional cp args
	if len(args) != 1 {
		return fmt.Errorf("rm: path argument required")
	}

	//var urls [1]*url.URL
	u, err := url.ParseRequestURI(args[0])
	if err != nil {
		return fmt.Errorf("parse error: %s", err)
	}
	if u.Host != "" && u.Scheme != "s3" {
		return fmt.Errorf("parse error: %s", u.String())
	}
	return s3.Bucket(u.Host).Delete(u.Path)
}
예제 #30
0
파일: vapp.go 프로젝트: RezaDKhan/terraform
func (v *VApp) DeleteMetadata(key string) (Task, error) {
	err := v.Refresh()
	if err != nil {
		return Task{}, fmt.Errorf("error refreshing vapp before running customization: %v", err)
	}

	if v.VApp.Children == nil {
		return Task{}, fmt.Errorf("vApp doesn't contain any children, aborting customization")
	}

	s, _ := url.ParseRequestURI(v.VApp.Children.VM[0].HREF)
	s.Path += "/metadata/" + key

	req := v.c.NewRequest(map[string]string{}, "DELETE", *s, nil)

	resp, err := checkResp(v.c.Http.Do(req))
	if err != nil {
		return Task{}, fmt.Errorf("error deleting Metadata: %s", err)
	}

	task := NewTask(v.c)

	if err = decodeBody(resp, task.Task); err != nil {
		return Task{}, fmt.Errorf("error decoding Task response: %s", err)
	}

	// The request was successful
	return *task, nil
}