當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。