本文整理汇总了Golang中net/url.URL.String方法的典型用法代码示例。如果您正苦于以下问题:Golang URL.String方法的具体用法?Golang URL.String怎么用?Golang URL.String使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类net/url.URL
的用法示例。
在下文中一共展示了URL.String方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: 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
}
示例2: 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)
}
示例3: 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
}
示例4: 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
}
示例5: tcpAddr
func tcpAddr(host string) string {
u := url.URL{
Scheme: "tcp",
Host: host,
}
return u.String()
}
示例6: 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
}
示例7: Detect_language
func Detect_language(q string) string {
var Url *url.URL
Url, err := url.Parse("https://www.googleapis.com")
if err != nil {
fmt.Println(err)
}
Url.Path += "/language/translate/v2/detect"
parameters := url.Values{}
parameters.Add("q", q)
parameters.Add("key", Google_key())
Url.RawQuery = parameters.Encode()
resp, err := http.Get(Url.String())
if err != nil {
fmt.Println(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
var data gtresponse
json.Unmarshal(body, &data)
lang := data.Data.Detections[0][0].Language
return lang
}
示例8: 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)
}
示例9: 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
}
示例10: fetch
func (f *dockerFetcher) fetch(u *url.URL) (*os.File, error) {
tmpDir, err := f.getTmpDir()
if err != nil {
return nil, err
}
defer os.RemoveAll(tmpDir)
registryURL := strings.TrimPrefix(u.String(), "docker://")
user, password := f.getCreds(registryURL)
config := docker2aci.RemoteConfig{
Username: user,
Password: password,
Insecure: f.InsecureFlags.AllowHTTP(),
CommonConfig: docker2aci.CommonConfig{
Squash: true,
OutputDir: tmpDir,
TmpDir: tmpDir,
Compression: d2acommon.NoCompression,
},
}
acis, err := docker2aci.ConvertRemoteRepo(registryURL, config)
if err != nil {
return nil, errwrap.Wrap(errors.New("error converting docker image to ACI"), err)
}
aciFile, err := os.Open(acis[0])
if err != nil {
return nil, errwrap.Wrap(errors.New("error opening squashed ACI file"), err)
}
return aciFile, nil
}
示例11: 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
}
示例12: 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
}
示例13: 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
}
}
}
示例14: siteRoot
func siteRoot(u *url.URL) string {
uu := url.URL{
Scheme: u.Scheme,
Host: u.Host,
}
return uu.String()
}
示例15: 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
}