当前位置: 首页>>代码示例>>Golang>>正文


Golang url.URL类代码示例

本文整理汇总了Golang中net/url.URL的典型用法代码示例。如果您正苦于以下问题:Golang URL类的具体用法?Golang URL怎么用?Golang URL使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了URL类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: siteRoot

func siteRoot(u *url.URL) string {
	uu := url.URL{
		Scheme: u.Scheme,
		Host:   u.Host,
	}
	return uu.String()
}
开发者ID:fanyang01,项目名称:crawler,代码行数:7,代码来源:site.go

示例2: moveBucketToHost

// moveBucketToHost moves the bucket name from the URI path to URL host.
func moveBucketToHost(u *url.URL, bucket string) {
	u.Host = bucket + "." + u.Host
	u.Path = strings.Replace(u.Path, "/{Bucket}", "", -1)
	if u.Path == "" {
		u.Path = "/"
	}
}
开发者ID:ColourboxDevelopment,项目名称:aws-sdk-go,代码行数:8,代码来源:host_style_bucket.go

示例3: doGet

func (s *Client) doGet(u url.URL) (*FileReader, error) {
	r, e := http.NewRequest("GET", u.String(), nil)
	if e != nil {
		return nil, e
	}
	return doRequest(r, s.AppToken, s.AccessToken)
}
开发者ID:puspesh,项目名称:cdfs,代码行数:7,代码来源:db.go

示例4: NewClientHandler

func NewClientHandler(c *oidc.Client, issuer string, cbURL url.URL) http.Handler {
	mux := http.NewServeMux()

	oob := cbURL.String() == client.OOBRedirectURI

	issuerURL, err := url.Parse(issuer)
	if err != nil {
		log.Fatalf("Could not parse issuer url: %v", err)
	}

	mux.HandleFunc("/", handleIndexFunc(oob))
	mux.HandleFunc("/login", handleLoginFunc(c))
	mux.HandleFunc("/register", handleRegisterFunc(c))
	if cbURL.String() != client.OOBRedirectURI {
		mux.HandleFunc(cbURL.Path, handleCallbackFunc(c))
	} else {
		mux.HandleFunc("/callback", handleCallbackFunc(c))
	}

	resendURL := *issuerURL
	resendURL.Path = "/resend-verify-email"

	mux.HandleFunc("/resend", handleResendFunc(c, *issuerURL, resendURL, cbURL))
	return mux
}
开发者ID:GamerockSA,项目名称:dex,代码行数:25,代码来源:main.go

示例5: RemoveRoute

func (r *fakeRouter) RemoveRoute(name string, address *url.URL) error {
	backendName, err := router.Retrieve(name)
	if err != nil {
		return err
	}
	if !r.HasBackend(backendName) {
		return router.ErrBackendNotFound
	}
	r.mutex.Lock()
	defer r.mutex.Unlock()
	if r.failuresByIp[address.String()] {
		return ErrForcedFailure
	}
	index := -1
	routes := r.backends[backendName]
	for i := range routes {
		if routes[i] == address.String() {
			index = i
			break
		}
	}
	if index < 0 {
		return router.ErrRouteNotFound
	}
	routes[index] = routes[len(routes)-1]
	r.backends[backendName] = routes[:len(routes)-1]
	return nil
}
开发者ID:zhenruyan,项目名称:tsuru,代码行数:28,代码来源:router.go

示例6: ValidRedirectURL

func (c Client) ValidRedirectURL(u *url.URL) (url.URL, error) {
	if c.Public {
		if u == nil {
			return url.URL{}, ErrorInvalidRedirectURL
		}
		if u.String() == OOBRedirectURI {
			return *u, nil
		}

		if u.Scheme != "http" {
			return url.URL{}, ErrorInvalidRedirectURL
		}

		hostPort := strings.Split(u.Host, ":")
		if len(hostPort) != 2 {
			return url.URL{}, ErrorInvalidRedirectURL
		}

		if hostPort[0] != "localhost" || u.Path != "" || u.RawPath != "" || u.RawQuery != "" || u.Fragment != "" {
			return url.URL{}, ErrorInvalidRedirectURL
		}

		return *u, nil
	}

	return ValidRedirectURL(u, c.Metadata.RedirectURIs)
}
开发者ID:cgenuity,项目名称:dex,代码行数:27,代码来源:client.go

示例7: main

func main() {
	flag.Parse()
	log.SetFlags(0)

	interrupt := make(chan os.Signal, 1)
	signal.Notify(interrupt, os.Interrupt)

	u := url.URL{Scheme: "ws", Host: *addr, Path: "/echo"}
	log.Printf("connecting to %s", u.String())

	c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
	if err != nil {
		log.Fatal("dial:", err)
	}
	defer c.Close()

	done := make(chan struct{})

	go func() {
		defer c.Close()
		defer close(done)
		for {
			_, message, err := c.ReadMessage()
			if err != nil {
				log.Println("read:", err)
				return
			}
			log.Printf("recv: %s", message)
		}
	}()

	ticker := time.NewTicker(time.Second)
	defer ticker.Stop()

	for {
		select {
		case t := <-ticker.C:
			err := c.WriteMessage(websocket.TextMessage, []byte(t.String()))
			if err != nil {
				log.Println("write:", err)
				return
			}
		case <-interrupt:
			log.Println("interrupt")
			// To cleanly close a connection, a client should send a close
			// frame and wait for the server to close the connection.
			err := c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
			if err != nil {
				log.Println("write close:", err)
				return
			}
			select {
			case <-done:
			case <-time.After(time.Second):
			}
			c.Close()
			return
		}
	}
}
开发者ID:CNDonny,项目名称:scope,代码行数:60,代码来源:client.go

示例8: SignAmazonUrl

func SignAmazonUrl(origUrl *url.URL, api AmazonProductAPI) (signedUrl string, err error) {

	escapeUrl := strings.Replace(origUrl.RawQuery, ",", "%2C", -1)
	escapeUrl = strings.Replace(escapeUrl, ":", "%3A", -1)

	params := strings.Split(escapeUrl, "&")
	sort.Strings(params)
	sortedParams := strings.Join(params, "&")

	toSign := fmt.Sprintf("GET\n%s\n%s\n%s", origUrl.Host, origUrl.Path, sortedParams)

	hasher := hmac.New(sha256.New, []byte(api.SecretKey))
	_, err = hasher.Write([]byte(toSign))
	if err != nil {
		return "", err
	}

	hash := base64.StdEncoding.EncodeToString(hasher.Sum(nil))

	hash = url.QueryEscape(hash)

	newParams := fmt.Sprintf("%s&Signature=%s", sortedParams, hash)

	origUrl.RawQuery = newParams

	return origUrl.String(), nil
}
开发者ID:matthistuff,项目名称:go-amazon-product-api,代码行数:27,代码来源:urlgen.go

示例9: connectStream

// connectStream is the internal version of ConnectStream. It differs from
// ConnectStream only in that it will not retry the connection if it encounters
// discharge-required error.
func (st *state) connectStream(path string, attrs url.Values) (base.Stream, error) {
	path, err := apiPath(st.modelTag, path)
	if err != nil {
		return nil, errors.Trace(err)
	}
	target := url.URL{
		Scheme:   "wss",
		Host:     st.addr,
		Path:     path,
		RawQuery: attrs.Encode(),
	}
	cfg, err := websocket.NewConfig(target.String(), "http://localhost/")
	if st.tag != "" {
		cfg.Header = utils.BasicAuthHeader(st.tag, st.password)
	}
	if st.nonce != "" {
		cfg.Header.Set(params.MachineNonceHeader, st.nonce)
	}
	// Add any cookies because they will not be sent to websocket
	// connections by default.
	st.addCookiesToHeader(cfg.Header)

	cfg.TlsConfig = st.tlsConfig
	connection, err := websocketDialConfig(cfg)
	if err != nil {
		return nil, err
	}
	if err := readInitialStreamError(connection); err != nil {
		return nil, errors.Trace(err)
	}
	return connection, nil
}
开发者ID:bac,项目名称:juju,代码行数:35,代码来源:apiclient.go

示例10: getConfigOverrides

func getConfigOverrides(uri *url.URL) (*kube_client_cmd.ConfigOverrides, error) {
	kubeConfigOverride := kube_client_cmd.ConfigOverrides{
		ClusterInfo: kube_client_cmd_api.Cluster{
			APIVersion: APIVersion,
		},
	}
	if len(uri.Scheme) != 0 && len(uri.Host) != 0 {
		kubeConfigOverride.ClusterInfo.Server = fmt.Sprintf("%s://%s", uri.Scheme, uri.Host)
	}

	opts := uri.Query()

	if len(opts["apiVersion"]) >= 1 {
		kubeConfigOverride.ClusterInfo.APIVersion = opts["apiVersion"][0]
	}

	if len(opts["insecure"]) > 0 {
		insecure, err := strconv.ParseBool(opts["insecure"][0])
		if err != nil {
			return nil, err
		}
		kubeConfigOverride.ClusterInfo.InsecureSkipTLSVerify = insecure
	}

	return &kubeConfigOverride, nil
}
开发者ID:kubernetes,项目名称:contrib,代码行数:26,代码来源:kubernetes.go

示例11: performHandshakeAndValidation

func performHandshakeAndValidation(conn *tls.Conn, uri *url.URL) error {
	if err := conn.Handshake(); err != nil {
		return err
	}

	cs := conn.ConnectionState()
	if !cs.NegotiatedProtocolIsMutual || cs.NegotiatedProtocol != protocol.ProtocolName {
		return fmt.Errorf("protocol negotiation error")
	}

	q := uri.Query()
	relayIDs := q.Get("id")
	if relayIDs != "" {
		relayID, err := syncthingprotocol.DeviceIDFromString(relayIDs)
		if err != nil {
			return fmt.Errorf("relay address contains invalid verification id: %s", err)
		}

		certs := cs.PeerCertificates
		if cl := len(certs); cl != 1 {
			return fmt.Errorf("unexpected certificate count: %d", cl)
		}

		remoteID := syncthingprotocol.NewDeviceID(certs[0].Raw)
		if remoteID != relayID {
			return fmt.Errorf("relay id does not match. Expected %v got %v", relayID, remoteID)
		}
	}

	return nil
}
开发者ID:hernad,项目名称:syncthing,代码行数:31,代码来源:static.go

示例12: createDeployment

func createDeployment(c *Configuration, deploymentURL *url.URL, data url.Values) (string, error) {
	req, err := http.NewRequest("POST", deploymentURL.String(), bytes.NewBufferString(data.Encode()))
	req.Header.Set(apiTokenHeaderName, c.ApiToken)
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

	resp, err := http.DefaultTransport.RoundTrip(req)
	if err != nil {
		return "", err
	}

	if resp.StatusCode != http.StatusSeeOther {
		defer resp.Body.Close()
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			return "", err
		}
		return "", UnexpectedResponse{resp.StatusCode, string(body)}
	}

	location := resp.Header.Get("Location")
	if location == "" {
		return "", fmt.Errorf("createDeployment: no Location header is response")
	}
	return location, nil
}
开发者ID:Wind0r,项目名称:toni,代码行数:25,代码来源:deploy.go

示例13: streamDeploymentLog

func streamDeploymentLog(c *Configuration, deploymentLogURL *url.URL) error {
	urlStr := deploymentLogURL.String()
	wsHeaders := http.Header{"Origin": {c.Host}, apiTokenHeaderName: {c.ApiToken}}

	wsConn, _, err := websocket.DefaultDialer.Dial(urlStr, wsHeaders)
	if err != nil {
		return err
	}

	logs := make(chan deploy.LogEntry)
	defer func() {
		close(logs)
	}()

	go deploy.ConsoleLogger(logs)

	for {
		entry := deploy.LogEntry{}
		err := wsConn.ReadJSON(&entry)
		if err == io.EOF {
			break
		}
		if err != nil {
			return err
		}

		logs <- entry
	}

	return nil
}
开发者ID:Wind0r,项目名称:toni,代码行数:31,代码来源:deploy.go

示例14: killDeployment

func killDeployment(c *Configuration, deploymentKillURL *url.URL) error {
	req, err := http.NewRequest("POST", deploymentKillURL.String(), &bytes.Buffer{})
	req.Header.Set(apiTokenHeaderName, c.ApiToken)

	_, err = http.DefaultTransport.RoundTrip(req)
	return err
}
开发者ID:Wind0r,项目名称:toni,代码行数:7,代码来源:deploy.go

示例15: fetchImageFrom

func (f *dockerFetcher) fetchImageFrom(u *url.URL, latest bool) (string, error) {
	if !f.InsecureFlags.SkipImageCheck() {
		return "", fmt.Errorf("signature verification for docker images is not supported (try --insecure-options=image)")
	}

	if f.Debug {
		log.Printf("fetching image from %s", u.String())
	}

	aciFile, err := f.fetch(u)
	if err != nil {
		return "", err
	}
	// At this point, the ACI file is removed, but it is kept
	// alive, because we have an fd to it opened.
	defer aciFile.Close()

	key, err := f.S.WriteACI(aciFile, latest)
	if err != nil {
		return "", err
	}

	// TODO(krnowak): Consider dropping the signature URL part
	// from store.Remote. It is not used anywhere and the data
	// stored here is useless.
	newRem := store.NewRemote(u.String(), ascURLFromImgURL(u).String())
	newRem.BlobKey = key
	newRem.DownloadTime = time.Now()
	err = f.S.WriteRemote(newRem)
	if err != nil {
		return "", err
	}

	return key, nil
}
开发者ID:coderhaoxin,项目名称:rkt,代码行数:35,代码来源:dockerfetcher.go


注:本文中的net/url.URL类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。