// urlParserPostgreSQL parses the options the same way official lib/pg does:
// https://godoc.org/github.com/lib/pq#hdr-Connection_String_Parameters
// After parsed, they are set to ConnectionDetails instance
480723
func urlParserPostgreSQL(cd *ConnectionDetails) error {
	var err error
	name := cd.URL
	if strings.HasPrefix(name, "postgres://") || strings.HasPrefix(name, "postgresql://") {
		name, err = pg.ParseURL(name)
		if err != nil {
			return err
		}
	}

	o := make(values)
	if err := parseOpts(name, o); err != nil {
		return err
	}

	if dbname, ok := o["dbname"]; ok {
		cd.Database = dbname
	}
	if host, ok := o["host"]; ok {
		cd.Host = host
	}
	if password, ok := o["password"]; ok {
		cd.Password = password
	}
	if user, ok := o["user"]; ok {
		cd.User = user
	}
	if port, ok := o["port"]; ok {
		cd.Port = port
	}

	options := []string{"sslmode", "fallback_application_name", "connect_timeout", "sslcert", "sslkey", "sslrootcert"}

	for i := range options {
		if opt, ok := o[options[i]]; ok {
			cd.Options[options[i]] = opt
		}
	}

	return nil
}
294892
func ParsePGPUpdateChainLink(b GenericChainLink) (ret *PGPUpdateChainLink, err error) {
	var kid keybase1.KID

	pgpUpdate := b.UnmarshalPayloadJSON().AtPath("body.pgp_update")

	if pgpUpdate.IsNil() {
		err = ChainLinkError{fmt.Sprintf("missing pgp_update section @%s", b.ToDebugString())}
		return
	}

	if kid, err = GetKID(pgpUpdate.AtKey("kid")); err != nil {
		err = ChainLinkError{fmt.Sprintf("Missing kid @%s: %s", b.ToDebugString(), err)}
		return
	}

	ret = &PGPUpdateChainLink{b, kid}

	if fh := ret.GetPGPFullHash(); fh == "" {
		err = ChainLinkError{fmt.Sprintf("Missing full_hash @%s", b.ToDebugString())}
		ret = nil
		return
	}

	return
}
604241
func buildURLParams(userURL string, params map[string]string) (string, error) {
	parsedURL, err := url.Parse(userURL)

	if err != nil {
		return "", err
	}

	parsedQuery, err := url.ParseQuery(parsedURL.RawQuery)

	if err != nil {
		return "", nil
	}

	for key, value := range params {
		parsedQuery.Set(key, value)
	}

	return addQueryParams(parsedURL, parsedQuery), nil
}
1373822
func parseOptions(dsn string) (server string, opts serverOptions, err error) {
	p, err := url.Parse(dsn)
	if err != nil {
		return "", serverOptions{}, err
	}

	// Grab known options from the query string
	q := p.Query()
	opts.id = q.Get("id")
	opts.insecure = opts.id != "" || queryBool(q, "insecure")
	opts.noAnnounce = queryBool(q, "noannounce")
	opts.noLookup = queryBool(q, "nolookup")

	// Check for disallowed combinations
	if p.Scheme == "http" {
		if !opts.insecure {
			return "", serverOptions{}, errors.New("http without insecure not supported")
		}
		if !opts.noAnnounce {
			return "", serverOptions{}, errors.New("http without noannounce not supported")
		}
	} else if p.Scheme != "https" {
		return "", serverOptions{}, errors.New("unsupported scheme " + p.Scheme)
	}

	// Remove the query string
	p.RawQuery = ""
	server = p.String()

	return
}
1305328
func (r *Router) ServeHTTP(res http.ResponseWriter, req *http.Request) {
	c := r.pool.Get().(*Context)
	c.init(res, req)
	if r.UseEscapedPath {
		c.handlers, c.pnames = r.find(req.Method, r.normalizeRequestPath(req.URL.EscapedPath()), c.pvalues)
		for i, v := range c.pvalues {
			c.pvalues[i], _ = url.QueryUnescape(v)
		}
	} else {
		c.handlers, c.pnames = r.find(req.Method, r.normalizeRequestPath(req.URL.Path), c.pvalues)
	}
	if err := c.Next(); err != nil {
		r.handleError(c, err)
	}
	r.pool.Put(c)
}
1230078
func ParseRedisURL(url string) (host, password string, db int, err error) {
	// redis://pwd@host/db

	var u *neturl.URL
	u, err = neturl.Parse(url)
	if err != nil {
		return
	}
	if u.Scheme != "redis" {
		err = errors.New("No redis scheme found")
		return
	}

	if u.User != nil {
		var exists bool
		password, exists = u.User.Password()
		if !exists {
			password = u.User.Username()
		}
	}

	host = u.Host

	parts := strings.Split(u.Path, "/")
	if len(parts) == 1 {
		db = 0 //default redis db
	} else {
		db, err = strconv.Atoi(parts[1])
		if err != nil {
			db, err = 0, nil //ignore err here
		}
	}

	return
}
1133442
func postgresConnStr(cfg migrateConfig) string {
	connStrs := []string{
		fmt.Sprintf("user=%s", cfg.User),
	}

	if len(cfg.Pass) > 0 {
		connStrs = append(connStrs, fmt.Sprintf("password=%s", cfg.Pass))
	}

	connStrs = append(connStrs, []string{
		fmt.Sprintf("host=%s", cfg.Host),
		fmt.Sprintf("port=%d", cfg.Port),
		fmt.Sprintf("dbname=%s", cfg.DBName),
	}...)

	if len(cfg.SSLMode) > 0 {
		connStrs = append(connStrs, fmt.Sprintf("sslmode=%s", cfg.SSLMode))
	}

	return strings.Join(connStrs, " ")
}
1182023
func urlParse(name string) *url.URL {
	var info os.FileInfo

	u, err := url.Parse(name)
	if err == nil && u.Scheme == "" {
		info, err = os.Stat(u.Path)
		if err == nil && info.IsDir() {
			u.Scheme = ArchiveScheme // special case for IsDir()
			return u
		}
	}

	u, err = url.Parse(strings.TrimPrefix(name, "/")) // must appear to be an absolute path or hgfs errors
	if err != nil {
		u = &url.URL{Path: name}
	}

	if u.Scheme == "" {
		ix := strings.Index(u.Path, "/")
		if ix > 0 {
			u.Scheme = u.Path[:ix]
			u.Path = u.Path[ix:]
		}
	}

	return u
}
556700
func (d *domainClient) GetRequestPostData(ctx context.Context, args *GetRequestPostDataArgs) (reply *GetRequestPostDataReply, err error) {
	reply = new(GetRequestPostDataReply)
	if args != nil {
		err = rpcc.Invoke(ctx, "Network.getRequestPostData", args, reply, d.conn)
	} else {
		err = rpcc.Invoke(ctx, "Network.getRequestPostData", nil, reply, d.conn)
	}
	if err != nil {
		err = &internal.OpError{Domain: "Network", Op: "GetRequestPostData", Err: err}
	}
	return
}
636763
func (inv *Investigate) PostParse(subUri string, body io.Reader, v interface{}) error {
	resp, err := inv.Post(subUri, body)

	if err != nil {
		inv.Log(err.Error())
		return err
	}

	err = inv.parseBody(resp.Body, v)

	if err != nil {
		inv.Log(err.Error())
	}

	return err
}
741555
func PostJSON(uri string, obj interface{}) ([]byte, error) {
	jsonData, err := json.Marshal(obj)
	if err != nil {
		return nil, err
	}

	jsonData = bytes.Replace(jsonData, []byte("\\u003c"), []byte("<"), -1)
	jsonData = bytes.Replace(jsonData, []byte("\\u003e"), []byte(">"), -1)
	jsonData = bytes.Replace(jsonData, []byte("\\u0026"), []byte("&"), -1)

	body := bytes.NewBuffer(jsonData)
	response, err := http.Post(uri, "application/json;charset=utf-8", body)
	if err != nil {
		return nil, err
	}
	defer response.Body.Close()

	if response.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("http get error : uri=%v , statusCode=%v", uri, response.StatusCode)
	}
	return ioutil.ReadAll(response.Body)
}
1008630
func pprintAddr(listeners []net.Listener) []byte {
	var out bytes.Buffer
	for i, l := range listeners {
		if i != 0 {
			fmt.Fprint(&out, ", ")
		}
		fmt.Fprint(&out, l.Addr())
	}
	return out.Bytes()
}
476719
func NewTHttpPostClientWithOptions(urlstr string, options THttpClientOptions) (TTransport, error) {
	return NewTHttpClientWithOptions(urlstr, options)
}
1336263
func (i *Image) parseResponseFromURL(u string, result interface{}) error {
	resp, err := i.getResponseFromURL(u)
	if err != nil {
		return err
	}

	defer resp.Body.Close()

	dec := json.NewDecoder(resp.Body)
	if err := dec.Decode(&result); err != nil {
		return err
	}

	return nil
}
291298
func (l *Client) PrepUrl(endpoint string, params url.Values, dataKey bool) (string, error) {
	// parse the url into native http.URL
	url, err := url.Parse(fmt.Sprintf("%s/%s", l.BaseUrl(), endpoint))
	if err != nil {
		return "", err
	}

	values := url.Query()

	// add the api key
	if params != nil {
		for key, val := range params {
			for _, v := range val {
				values.Add(key, v)
			}
		}
	}

	// if there is a data key use that by default, if not use the main api key
	// assumption here is that if its a data key there are specific reasons
	if dataKey {
		values.Add("key", l.dataApiKey)
	} else {
		values.Add("key", l.apiKey)
	}

	// encode the final url so we can return string and make call
	url.RawQuery = values.Encode()

	return url.String(), nil
}
871259
func ParseHostURL(host string) (*url.URL, error) {
	protoAddrParts := strings.SplitN(host, "://", 2)
	if len(protoAddrParts) == 1 {
		return nil, fmt.Errorf("unable to parse docker host `%s`", host)
	}

	var basePath string
	proto, addr := protoAddrParts[0], protoAddrParts[1]
	if proto == "tcp" {
		parsed, err := url.Parse("tcp://" + addr)
		if err != nil {
			return nil, err
		}
		addr = parsed.Host
		basePath = parsed.Path
	}
	return &url.URL{
		Scheme: proto,
		Host:   addr,
		Path:   basePath,
	}, nil
}
588417
func parseRepoURL(image string) (*parsedURL, error) {
	parsed, err := url.Parse("https://" + image)
	if err != nil {
		return nil, fmt.Errorf("error parsing image %s %v", image, err)
	}
	splitURL := ecrPattern.FindStringSubmatch(parsed.Hostname())
	if len(splitURL) == 0 {
		return nil, fmt.Errorf("%s is not a valid ECR repository URL", parsed.Hostname())
	}
	return &parsedURL{
		registryID: splitURL[1],
		region:     splitURL[3],
		registry:   parsed.Hostname(),
	}, nil
}