Example #1
0
// GetHook is a heper function that retrieves a hook by
// hostname. To do this, it will retrieve a list of all hooks
// and iterate through the list.
func GetHook(client *github.Client, owner, name, rawurl string) (*github.Hook, error) {
	hooks, _, err := client.Repositories.ListHooks(owner, name, nil)
	if err != nil {
		return nil, err
	}
	newurl, err := url.Parse(rawurl)
	if err != nil {
		fmt.Println("error parsing new hook url", rawurl, err)
		return nil, err
	}
	for _, hook := range hooks {
		hookurl, ok := hook.Config["url"].(string)
		if !ok {
			continue
		}
		oldurl, err := url.Parse(hookurl)
		if err != nil {
			fmt.Println("error parsing old hook url", hookurl, err)
			continue
		}
		if newurl.Host == oldurl.Host {
			return &hook, nil
		}
	}
	return nil, nil
}
func TestEncodedSlashes(t *testing.T) {
	var seen string
	backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(200)
		seen = r.RequestURI
	}))
	defer backend.Close()

	b, _ := url.Parse(backend.URL)
	proxyHandler := NewReverseProxy(b)
	setProxyDirector(proxyHandler)
	frontend := httptest.NewServer(proxyHandler)
	defer frontend.Close()

	f, _ := url.Parse(frontend.URL)
	encodedPath := "/a%2Fb/?c=1"
	getReq := &http.Request{URL: &url.URL{Scheme: "http", Host: f.Host, Opaque: encodedPath}}
	_, err := http.DefaultClient.Do(getReq)
	if err != nil {
		t.Fatalf("err %s", err)
	}
	if seen != encodedPath {
		t.Errorf("got bad request %q expected %q", seen, encodedPath)
	}
}
Example #3
0
// TODO: This could use a unit test.
func parseSwarm(hostURL string, h *host.Host) (string, error) {
	swarmOptions := h.HostOptions.SwarmOptions

	if !swarmOptions.Master {
		return "", fmt.Errorf("%q is not a swarm master. The --swarm flag is intended for use with swarm masters", h.Name)
	}

	u, err := url.Parse(swarmOptions.Host)
	if err != nil {
		return "", fmt.Errorf("There was an error parsing the url: %s", err)
	}
	parts := strings.Split(u.Host, ":")
	swarmPort := parts[1]

	// get IP of machine to replace in case swarm host is 0.0.0.0
	mURL, err := url.Parse(hostURL)
	if err != nil {
		return "", fmt.Errorf("There was an error parsing the url: %s", err)
	}

	mParts := strings.Split(mURL.Host, ":")
	machineIP := mParts[0]

	hostURL = fmt.Sprintf("tcp://%s:%s", machineIP, swarmPort)

	return hostURL, nil
}
Example #4
0
// newRequest is used to create a new request
func (c *Client) newRequest(method, path string) *request {
	base, _ := url.Parse(c.config.Address)
	u, _ := url.Parse(path)
	r := &request{
		config: &c.config,
		method: method,
		url: &url.URL{
			Scheme: base.Scheme,
			Host:   base.Host,
			Path:   u.Path,
		},
		params: make(map[string][]string),
	}
	if c.config.Region != "" {
		r.params.Set("region", c.config.Region)
	}
	if c.config.WaitTime != 0 {
		r.params.Set("wait", durToMsec(r.config.WaitTime))
	}

	// Add in the query parameters, if any
	for key, values := range u.Query() {
		for _, value := range values {
			r.params.Add(key, value)
		}
	}

	return r
}
Example #5
0
func (h *EssentialHeader) Construct(m map[string]interface{}) error {
	r := emap.Hmap(m)
	if alg, err := r.GetString("alg"); err == nil {
		h.Algorithm = jwa.SignatureAlgorithm(alg)
	}
	if h.Algorithm == "" {
		h.Algorithm = jwa.NoSignature
	}
	h.ContentType, _ = r.GetString("cty")
	h.KeyID, _ = r.GetString("kid")
	h.Type, _ = r.GetString("typ")
	h.X509CertThumbprint, _ = r.GetString("x5t")
	h.X509CertThumbprintS256, _ = r.GetString("x5t#256")
	if v, err := r.GetStringSlice("crit"); err != nil {
		h.Critical = v
	}
	if v, err := r.GetStringSlice("x5c"); err != nil {
		h.X509CertChain = v
	}
	if v, err := r.GetString("jku"); err == nil {
		u, err := url.Parse(v)
		if err == nil {
			h.JwkSetURL = u
		}
	}

	if v, err := r.GetString("x5u"); err == nil {
		u, err := url.Parse(v)
		if err == nil {
			h.X509Url = u
		}
	}

	return nil
}
Example #6
0
// ProxyFromEnvironment returns the URL of the proxy to use for a
// given request, as indicated by the environment variables
// HTTP_PROXY, HTTPS_PROXY and NO_PROXY (or the lowercase versions
// thereof). HTTPS_PROXY takes precedence over HTTP_PROXY for https
// requests.
//
// The environment values may be either a complete URL or a
// "host[:port]", in which case the "http" scheme is assumed.
// An error is returned if the value is a different form.
//
// A nil URL and nil error are returned if no proxy is defined in the
// environment, or a proxy should not be used for the given request,
// as defined by NO_PROXY.
//
// As a special case, if req.URL.Host is "localhost" (with or without
// a port number), then a nil URL and nil error will be returned.
func ProxyFromEnvironment(req *Request) (*url.URL, error) {
	var proxy string
	if req.URL.Scheme == "https" {
		proxy = httpsProxyEnv.Get()
	}
	if proxy == "" {
		proxy = httpProxyEnv.Get()
	}
	if proxy == "" {
		return nil, nil
	}
	if !useProxy(canonicalAddr(req.URL)) {
		return nil, nil
	}
	proxyURL, err := url.Parse(proxy)
	if err != nil || !strings.HasPrefix(proxyURL.Scheme, "http") {
		// proxy was bogus. Try prepending "http://" to it and
		// see if that parses correctly. If not, we fall
		// through and complain about the original one.
		if proxyURL, err := url.Parse("http://" + proxy); err == nil {
			return proxyURL, nil
		}
	}
	if err != nil {
		return nil, fmt.Errorf("invalid proxy address %q: %v", proxy, err)
	}
	return proxyURL, nil
}
Example #7
0
// fetchImage will take an image as either a URL or a name string and import it
// into the store if found.
func fetchImage(img string, ds *cas.Store) (string, error) {
	// discover if it isn't a URL
	u, err := url.Parse(img)
	if err == nil && u.Scheme == "" {
		app, err := discovery.NewAppFromString(img)
		if globalFlags.Debug && err != nil {
			fmt.Printf("discovery: %s\n", err)
		}
		if err == nil {
			ep, err := discovery.DiscoverEndpoints(*app, true)
			if err != nil {
				return "", err
			}
			// TODO(philips): use all available mirrors
			if globalFlags.Debug {
				fmt.Printf("fetch: trying %v\n", ep.ACI)
			}
			img = ep.ACI[0]
			u, err = url.Parse(img)
		}
	}

	if err != nil { // download if it isn't a URL
		return "", fmt.Errorf("%s: not a valid URL or hash", img)
	}
	if u.Scheme != "http" && u.Scheme != "https" {
		return "", fmt.Errorf("%s: rkt only supports http or https URLs", img)
	}
	return fetchURL(img, ds)
}
Example #8
0
// scriptProxyConfig determines a proxy configuration for downloading
// scripts from a URL. For now, it uses environment variables passed in
// the strategy's environment. There is no preference given to either lowercase
// or uppercase form of the variable.
func scriptProxyConfig(build *api.Build) (*s2iapi.ProxyConfig, error) {
	httpProxy := ""
	httpsProxy := ""
	for _, env := range build.Spec.Strategy.SourceStrategy.Env {
		switch env.Name {
		case "HTTP_PROXY", "http_proxy":
			httpProxy = env.Value
		case "HTTPS_PROXY", "https_proxy":
			httpsProxy = env.Value
		}
	}
	if len(httpProxy) == 0 && len(httpsProxy) == 0 {
		return nil, nil
	}
	config := &s2iapi.ProxyConfig{}
	if len(httpProxy) > 0 {
		proxyURL, err := url.Parse(httpProxy)
		if err != nil {
			return nil, err
		}
		config.HTTPProxy = proxyURL
	}
	if len(httpsProxy) > 0 {
		proxyURL, err := url.Parse(httpsProxy)
		if err != nil {
			return nil, err
		}
		config.HTTPSProxy = proxyURL
	}
	return config, nil
}
Example #9
0
func (s *ExternalSuite) TestSwap(c *check.C) {
	backend1 := "b1"
	backend2 := "b2"
	r, err := router.Get("fake")
	c.Assert(err, check.IsNil)
	r.AddBackend(backend1)
	addr1, _ := url.Parse("http://127.0.0.1")
	r.AddRoute(backend1, addr1)
	r.AddBackend(backend2)
	addr2, _ := url.Parse("http://10.10.10.10")
	r.AddRoute(backend2, addr2)
	err = router.Swap(r, backend1, backend2)
	c.Assert(err, check.IsNil)
	routes1, err := r.Routes(backend1)
	c.Assert(err, check.IsNil)
	c.Assert(routes1, check.DeepEquals, []*url.URL{addr1})
	routes2, err := r.Routes(backend2)
	c.Assert(err, check.IsNil)
	c.Assert(routes2, check.DeepEquals, []*url.URL{addr2})
	name1, err := router.Retrieve(backend1)
	c.Assert(err, check.IsNil)
	c.Assert(name1, check.Equals, backend2)
	name2, err := router.Retrieve(backend2)
	c.Assert(err, check.IsNil)
	c.Assert(name2, check.Equals, backend1)
}
Example #10
0
func fileServeHandler(c web.C, w http.ResponseWriter, r *http.Request) {
	fileName := c.URLParams["name"]
	filePath := path.Join(Config.filesDir, fileName)

	err := checkFile(fileName)
	if err == NotFoundErr {
		notFoundHandler(c, w, r)
		return
	} else if err == BadMetadata {
		oopsHandler(c, w, r, RespAUTO, "Corrupt metadata.")
		return
	}

	if !Config.allowHotlink {
		referer := r.Header.Get("Referer")
		u, _ := url.Parse(referer)
		p, _ := url.Parse(Config.siteURL)
		if referer != "" && !sameOrigin(u, p) {
			w.WriteHeader(403)
			return
		}
	}

	w.Header().Set("Content-Security-Policy", Config.fileContentSecurityPolicy)

	http.ServeFile(w, r, filePath)
}
Example #11
0
// Tests domains that should (or should not) return true for a
// same-origin check.
func TestSameOrigin(t *testing.T) {
	var originTests = []struct {
		o1       string
		o2       string
		expected bool
	}{
		{"https://goji.io/", "https://goji.io", true},
		{"http://golang.org/", "http://golang.org/pkg/net/http", true},
		{"https://goji.io/", "http://goji.io", false},
		{"https://goji.io:3333/", "http://goji.io:4444", false},
	}

	for _, origins := range originTests {
		a, err := url.Parse(origins.o1)
		if err != nil {
			t.Fatal(err)
		}

		b, err := url.Parse(origins.o2)
		if err != nil {
			t.Fatal(err)
		}

		if sameOrigin(a, b) != origins.expected {
			t.Fatalf("origin checking failed: %v and %v, expected %v",
				origins.o1, origins.o2, origins.expected)
		}
	}
}
Example #12
0
func ValidateUri(baseUri string, redirectUri string) bool {
	if baseUri == "" || redirectUri == "" {
		log.Print("urls cannot be blank.\n")
		return false
	}

	base, err := url.Parse(baseUri)
	if err != nil {
		log.Printf("Error: %s\n", err)
		return false
	}

	redirect, err := url.Parse(redirectUri)
	if err != nil {
		log.Printf("Error: %s\n", err)
		return false
	}

	// must not have fragment
	if base.Fragment != "" || redirect.Fragment != "" {
		log.Print("Error: url must not include fragment.\n")
		return false
	}

	if base.Scheme == redirect.Scheme && base.Host == redirect.Host && len(redirect.Path) >= len(base.Path) && strings.HasPrefix(redirect.Path, base.Path) {
		return true
	}

	log.Printf("urls don't validate: %s / %s\n", baseUri, redirectUri)
	return false
}
Example #13
0
func prepareHandler(w http.ResponseWriter, r *http.Request) {
	if h := r.Header.Get("X-Forwarded-Host"); h != "" {
		baseUrl, _ = url.Parse("http://" + h)
	} else {
		baseUrl, _ = url.Parse("http://" + r.Host)
	}
}
Example #14
0
func init() {
	err := envconfig.Process("HELEN", &Constants)
	if err != nil {
		logrus.Fatal(err)
	}

	if Constants.SteamDevAPIKey == "" {
		logrus.Warning("Steam api key not provided, setting SteamApiMockUp to true")
	}
	if Constants.PublicAddress == "" {
		Constants.PublicAddress = "http://" + Constants.ListenAddress
	}
	if Constants.MockupAuth {
		logrus.Warning("Mockup authentication enabled.")
	}

	_, err = url.Parse(Constants.PublicAddress)
	if err != nil {
		logrus.Fatal("Couldn't parse HELEN_PUBLIC_ADDR - ", err)
	}
	_, err = url.Parse(Constants.LoginRedirectPath)
	if err != nil {
		logrus.Fatal("Couldn't parse HELEN_SERVER_REDIRECT_PATH - ", err)
	}

	if Constants.GeoIP {
		logrus.Info("GeoIP support enabled")
	}
}
Example #15
0
func (response HTTPResponse) canRedirectWithConn(conn *Conn) bool {

	targetUrl, targetUrlError := url.Parse(conn.domain)
	if targetUrlError != nil {
		return false
	}

	redirectUrl, redirectUrlError := url.Parse(response.Headers["location"].(string))
	if redirectUrlError != nil {
		return false
	}

	remoteIpAddress, _, remoteIpAddressErr := net.SplitHostPort(conn.RemoteAddr().String())
	if remoteIpAddressErr != nil {
		return false
	}

	relativePath := redirectUrl.Host == ""
	matchesHost := (strings.Contains(redirectUrl.Host, targetUrl.Host)) || (redirectUrl.Host == remoteIpAddress)
	matchesProto := (conn.isTls && redirectUrl.Scheme == "https") || (!conn.isTls && redirectUrl.Scheme == "http")

	// Either explicit keep-alive or HTTP 1.1, which uses persistent connections by default
	var keepAlive bool
	if response.Headers["Connection"] != nil {
		keepAlive = strings.EqualFold(response.Headers["Connection"].(string), "keep-alive")
	} else {
		keepAlive = response.VersionMajor == 1 && response.VersionMinor == 1

	}

	return (relativePath && keepAlive) || (!relativePath && keepAlive && matchesHost && matchesProto)
}
Example #16
0
func NewSignatureTest() *SignatureTest {
	opts := NewOptions()
	opts.CookieSecret = "cookie secret"
	opts.ClientID = "client ID"
	opts.ClientSecret = "client secret"
	opts.EmailDomains = []string{"acm.org"}

	authenticator := &SignatureAuthenticator{}
	upstream := httptest.NewServer(
		http.HandlerFunc(authenticator.Authenticate))
	upstream_url, _ := url.Parse(upstream.URL)
	opts.Upstreams = append(opts.Upstreams, upstream.URL)

	providerHandler := func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte(`{"access_token": "my_auth_token"}`))
	}
	provider := httptest.NewServer(http.HandlerFunc(providerHandler))
	provider_url, _ := url.Parse(provider.URL)
	opts.provider = NewTestProvider(provider_url, "mbland@acm.org")

	return &SignatureTest{
		opts,
		upstream,
		upstream_url.Host,
		provider,
		make(http.Header),
		httptest.NewRecorder(),
		authenticator,
	}
}
Example #17
0
// Create the server pool using the options given.
// We will place a Url option first, followed by any
// Server Options. We will randomize the server pool unlesss
// the NoRandomize flag is set.
func (nc *Conn) setupServerPool() error {
	nc.srvPool = make([]*srv, 0, srvPoolSize)
	if nc.Opts.Url != _EMPTY_ {
		u, err := url.Parse(nc.Opts.Url)
		if err != nil {
			return err
		}
		s := &srv{url: u}
		nc.srvPool = append(nc.srvPool, s)
	}

	var srvrs []string
	source := mrand.NewSource(time.Now().UnixNano())
	r := mrand.New(source)

	if nc.Opts.NoRandomize {
		srvrs = nc.Opts.Servers
	} else {
		in := r.Perm(len(nc.Opts.Servers))
		for _, i := range in {
			srvrs = append(srvrs, nc.Opts.Servers[i])
		}
	}
	for _, urlString := range srvrs {
		u, err := url.Parse(urlString)
		if err != nil {
			return err
		}
		s := &srv{url: u}
		nc.srvPool = append(nc.srvPool, s)
	}
	return nc.pickServer()
}
Example #18
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()
}
Example #19
0
// NewClient returns a new netlify API client
func NewClient(config *Config) *Client {
	client := &Client{}

	if config.BaseUrl != "" {
		client.BaseUrl, _ = url.Parse(config.BaseUrl)
	} else {
		client.BaseUrl, _ = url.Parse(defaultBaseURL)
	}

	if config.HttpClient != nil {
		client.client = config.HttpClient
	} else if config.AccessToken != "" {
		t := &oauth.Transport{
			Token: &oauth.Token{AccessToken: config.AccessToken},
		}
		client.client = t.Client()
	}

	if &config.UserAgent != nil {
		client.UserAgent = config.UserAgent
	} else {
		client.UserAgent = userAgent
	}

	if config.MaxConcurrentUploads != 0 {
		client.MaxConcurrentUploads = config.MaxConcurrentUploads
	} else {
		client.MaxConcurrentUploads = DefaultMaxConcurrentUploads
	}

	client.Sites = &SitesService{client: client}
	client.Deploys = &DeploysService{client: client}

	return client
}
Example #20
0
// NewClient returns a new GitHub API client.  If a nil httpClient is
// provided, http.DefaultClient will be used.  To use API methods which require
// authentication, provide an http.Client that will perform the authentication
// for you (such as that provided by the golang.org/x/oauth2 library).
func NewClient(httpClient *http.Client, apiURL ...string) *Client {
	if httpClient == nil {
		httpClient = http.DefaultClient
	}

	currentBaseURL := defaultBaseURL
	if len(apiURL) > 0 {
		currentBaseURL = apiURL[0]
	}
	baseURL, _ := url.Parse(currentBaseURL)
	uploadURL, _ := url.Parse(uploadBaseURL)

	c := &Client{client: httpClient, BaseURL: baseURL, UserAgent: userAgent, UploadURL: uploadURL}
	c.Activity = &ActivityService{client: c}
	c.Gists = &GistsService{client: c}
	c.Git = &GitService{client: c}
	c.Gitignores = &GitignoresService{client: c}
	c.Issues = &IssuesService{client: c}
	c.Organizations = &OrganizationsService{client: c}
	c.PullRequests = &PullRequestsService{client: c}
	c.Repositories = &RepositoriesService{client: c}
	c.Search = &SearchService{client: c}
	c.Users = &UsersService{client: c}
	c.Licenses = &LicensesService{client: c}
	return c
}
Example #21
0
func (r Client) Do(l Logger, req *http.Request) (resp *http.Response, err error) {
	//check bind remote ip
	if r.BindRemoteIp != "" {
		oldReqUrl := req.URL.String()
		oldReqUri, _ := url.Parse(oldReqUrl)

		newUrlStr := fmt.Sprintf("%s://%s%s", oldReqUri.Scheme, r.BindRemoteIp, oldReqUri.RequestURI())
		newUrl, _ := url.Parse(newUrlStr)

		req.URL = newUrl
		req.Header.Set("Host", oldReqUri.Host)
	}

	if l != nil {
		req.Header.Set("X-Reqid", l.ReqId())
	}

	req.Header.Set("User-Agent", UserAgent)
	resp, err = r.Client.Do(req)
	if err != nil {
		return
	}

	if l != nil {
		details := resp.Header["X-Log"]
		if len(details) > 0 {
			l.Xput(details)
		}
	}
	return
}
Example #22
0
func TestGetAuthCodeURL(t *testing.T) {
	ar := &osin.AuthorizeRequest{
		RedirectUri: mock.conf.RedirectURL,
		Client:      &osin.DefaultClient{Id: mock.conf.ClientID},
		Scope:       "scope",
		Type:        osin.CODE,
		State:       "state",
	}

	path := mock.GetAuthCodeURL(ar)
	t.Logf("Got auth code url: %s", path)
	parsed, err := url.Parse(path)
	require.Nil(t, err)

	redirect, err := url.QueryUnescape(parsed.Query().Get("redirect_uri"))
	require.Nil(t, err)

	parsed, err = url.Parse(redirect)
	t.Logf("Got redirect url: %s", redirect)
	require.Nil(t, err)
	q := parsed.Query()

	assert.Equal(t, ar.RedirectUri, q.Get(RedirectQueryParam))
	assert.Equal(t, ar.Client.GetId(), q.Get(ClientQueryParam))
	assert.Equal(t, ar.Scope, q.Get(ScopeQueryParam))
	assert.Equal(t, ar.State, q.Get(StateQueryParam))
	assert.Equal(t, string(ar.Type), q.Get(TypeQueryParam))
}
Example #23
0
func TestRouteConfig(t *testing.T) {
	opts, err := ProcessConfigFile("./configs/cluster.conf")
	if err != nil {
		t.Fatalf("Received an error reading route config file: %v\n", err)
	}

	golden := &Options{
		Host:               "apcera.me",
		Port:               4242,
		Username:           "derek",
		Password:           "bella",
		AuthTimeout:        1.0,
		ClusterHost:        "127.0.0.1",
		ClusterPort:        4244,
		ClusterUsername:    "route_user",
		ClusterPassword:    "top_secret",
		ClusterAuthTimeout: 1.0,
		LogFile:            "/tmp/nats_cluster_test.log",
		PidFile:            "/tmp/nats_cluster_test.pid",
	}

	// Setup URLs
	r1, _ := url.Parse("nats-route://foo:bar@apcera.me:4245")
	r2, _ := url.Parse("nats-route://foo:bar@apcera.me:4246")

	golden.Routes = []*url.URL{r1, r2}

	if !reflect.DeepEqual(golden, opts) {
		t.Fatalf("Options are incorrect.\nexpected: %+v\ngot: %+v",
			golden, opts)
	}
}
Example #24
0
func NewOauthProxy(proxyUrls []*url.URL, clientID string, clientSecret string, validator func(string) bool) *OauthProxy {
	login, _ := url.Parse("https://accounts.google.com/o/oauth2/auth")
	redeem, _ := url.Parse("https://accounts.google.com/o/oauth2/token")
	info, _ := url.Parse("https://www.googleapis.com/oauth2/v2/userinfo")
	serveMux := http.NewServeMux()
	for _, u := range proxyUrls {
		path := u.Path
		u.Path = ""
		log.Printf("mapping %s => %s", path, u)
		serveMux.Handle(path, httputil.NewSingleHostReverseProxy(u))
	}
	return &OauthProxy{
		CookieKey:  "_oauthproxy",
		CookieSeed: *cookieSecret,
		Validator:  validator,

		clientID:           clientID,
		clientSecret:       clientSecret,
		oauthScope:         "https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email",
		oauthRedemptionUrl: redeem,
		oauthLoginUrl:      login,
		oauthUserInfoUrl:   info,
		serveMux:           serveMux,
	}
}
func TestNewReverseProxy(t *testing.T) {
	backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(200)
		hostname, _, _ := net.SplitHostPort(r.Host)
		w.Write([]byte(hostname))
	}))
	defer backend.Close()

	backendURL, _ := url.Parse(backend.URL)
	backendHostname, backendPort, _ := net.SplitHostPort(backendURL.Host)
	backendHost := net.JoinHostPort(backendHostname, backendPort)
	proxyURL, _ := url.Parse(backendURL.Scheme + "://" + backendHost + "/")

	proxyHandler := NewReverseProxy(proxyURL)
	setProxyUpstreamHostHeader(proxyHandler, proxyURL)
	frontend := httptest.NewServer(proxyHandler)
	defer frontend.Close()

	getReq, _ := http.NewRequest("GET", frontend.URL, nil)
	res, _ := http.DefaultClient.Do(getReq)
	bodyBytes, _ := ioutil.ReadAll(res.Body)
	if g, e := string(bodyBytes), backendHostname; g != e {
		t.Errorf("got body %q; expected %q", g, e)
	}
}
Example #26
0
func CreatePlaceHandler(w http.ResponseWriter, r *http.Request) {
	sess, err := mgo.Dial(mongoDbUrl)
	place := new(Place)
	r.ParseForm()
	outingId := r.FormValue("outingId")
	outing, err := loadOuting(outingId)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	Name := r.FormValue("Name")
	MapLink, err := url.Parse(r.FormValue("MapLink"))
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	FoursquareLink, err := url.Parse(r.FormValue("FoursquareLink"))
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	place.Name = Name
	place.MapLink = MapLink
	place.FoursquareLink = FoursquareLink
	collection := sess.DB("mappuri").C("outings")
	outing.Places = append(outing.Places, *place)
	err = collection.UpdateId(bson.ObjectIdHex(outingId), &outing)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
}
Example #27
0
// GetBookmarkCounts call hatena bookmark count api.
func GetBookmarkCounts(urls []string) (map[string]int, error) {
	query := neturl.Values{}
	for _, url := range urls {
		u, err := neturl.Parse(url)
		if err != nil {
			return map[string]int{}, err
		}
		query.Add("url", u.String())
	}

	req, _ := neturl.Parse(EntryCountsAPIURL)
	req.RawQuery = query.Encode()

	res, err := http.Get(req.String())
	if err != nil {
		return map[string]int{}, err
	}

	body, _ := ioutil.ReadAll(res.Body)
	defer res.Body.Close()

	counts := map[string]int{}
	json.Unmarshal(body, &counts)
	return counts, nil
}
Example #28
0
// defaultServerURL is a modified copy of k8s.io/kubernets/pkg/client/restclient.DefaultServerURL.
// DefaultServerURL converts a host, host:port, or URL string to the default base server API path
// to use with a Client at a given API version following the standard conventions for a
// Kubernetes API.
func defaultServerURL(host string, defaultTLS bool) (*url.URL, error) {
	if host == "" {
		return nil, fmt.Errorf("host must be a URL or a host:port pair")
	}
	base := host
	hostURL, err := url.Parse(base)
	if err != nil {
		return nil, err
	}
	if hostURL.Scheme == "" {
		scheme := "http://"
		if defaultTLS {
			scheme = "https://"
		}
		hostURL, err = url.Parse(scheme + base)
		if err != nil {
			return nil, err
		}
		if hostURL.Path != "" && hostURL.Path != "/" {
			return nil, fmt.Errorf("host must be a URL or a host:port pair: %q", base)
		}
	}

	// REMOVED: versionedAPIPath computation.
	return hostURL, nil
}
Example #29
0
func NewSource(token, app, dir string) (source Source, err error) {
	client := newHerokuClient(token)

	source.Dir, err = os.Open(dir)
	if err != nil {
		return
	}

	sourceJson := new(SourceJSON)

	err = client.request(sourceRequest(app), &sourceJson)
	if err != nil {
		return
	}

	source.Get, err = url.Parse(sourceJson.SourceBlob.GetUrl)
	if err != nil {
		return
	}
	source.Put, err = url.Parse(sourceJson.SourceBlob.PutUrl)
	if err != nil {
		return
	}

	return
}
Example #30
0
func parseRequestURL(c *Client, r *Request) error {
	// Parsing request URL
	reqURL, err := url.Parse(r.URL)
	if err != nil {
		return err
	}

	// If Request.Url is relative path then added c.HostUrl into
	// the request URL otherwise Request.Url will be used as-is
	if !reqURL.IsAbs() {
		if !strings.HasPrefix(r.URL, "/") {
			r.URL = "/" + r.URL
		}

		reqURL, err = url.Parse(c.HostURL + r.URL)
		if err != nil {
			return err
		}
	}

	// Adding Query Param
	query := reqURL.Query()
	for k := range c.QueryParam {
		query.Set(k, c.QueryParam.Get(k))
	}
	for k := range r.QueryParam {
		query.Set(k, r.QueryParam.Get(k))
	}

	reqURL.RawQuery = query.Encode()
	r.URL = reqURL.String()

	return nil
}