// TODO: need a full link header parser for http://tools.ietf.org/html/rfc5988
198367
func HyperHeaderRelations(header http.Header, rels Relations) Relations {
	if rels == nil {
		rels = make(Relations)
	}

	link := header.Get("Link")
	if len(link) == 0 {
		return rels
	}

	for _, l := range strings.Split(link, ",") {
		l = strings.TrimSpace(l)
		segments := strings.Split(l, ";")

		if len(segments) < 2 {
			continue
		}

		if !strings.HasPrefix(segments[0], "<") || !strings.HasSuffix(segments[0], ">") {
			continue
		}

		url, err := url.Parse(segments[0][1 : len(segments[0])-1])
		if err != nil {
			continue
		}

		link := Hyperlink(url.String())

		for _, segment := range segments[1:] {
			switch strings.TrimSpace(segment) {
			case `rel="next"`:
				rels["next"] = link
			case `rel="prev"`:
				rels["prev"] = link
			case `rel="first"`:
				rels["first"] = link
			case `rel="last"`:
				rels["last"] = link
			}
		}
	}

	return rels
}
850611
func (l *Link) HTML() template.HTML {
	if l == nil {
		return ""
	}
	buf := bytes.Buffer{}
	if err := linkifyTemplate.Execute(&buf, l); err != nil {
		panic(err)
	}
	return template.HTML(buf.Bytes())
}
456192
func (r typeSpecReference) Link(scope Scope) (TypeSpec, error) {
	src := ast.TypeReference(r)
	t, err := scope.LookupType(src.Name)
	if err == nil {
		return t.Link(scope)
	}

	mname, iname := splitInclude(src.Name)
	if len(mname) == 0 {
		return nil, referenceError{
			Target:    src.Name,
			Line:      src.Line,
			ScopeName: scope.GetName(),
			Reason:    err,
		}
	}

	includedScope, err := getIncludedScope(scope, mname)
	if err != nil {
		return nil, referenceError{
			Target:    src.Name,
			Line:      src.Line,
			ScopeName: scope.GetName(),
			Reason:    err,
		}
	}

	t, err = typeSpecReference{Name: iname}.Link(includedScope)
	if err != nil {
		return nil, referenceError{
			Target:    src.Name,
			Line:      src.Line,
			ScopeName: scope.GetName(),
			Reason:    err,
		}
	}

	return t, nil
}
1101621
func (pt *ParseTime) RFC8xx1123(value string) (time.Time, error) {
	t, _, err := parseRFC8xx1123(value, pt.location)
	return t, err
}
30848
func (c *TokenController) LinkCallback(ctx *app.LinkCallbackTokenContext) error {
	redirectLocation, err := c.app.LinkService().Callback(ctx, ctx.RequestData, ctx.State, ctx.Code)
	if err != nil {
		return jsonapi.JSONErrorResponse(ctx, err)
	}
	ctx.ResponseData.Header().Set("Location", redirectLocation)
	return ctx.TemporaryRedirect()
}
1197918
func doLinksPage(w http.ResponseWriter, r *http.Request, n int, offset int) {
	w.Header().Add("Content-Type", htmlContentType)
	w.WriteHeader(http.StatusOK)

	w.Write([]byte("<html><head><title>Links</title></head><body>"))
	for i := 0; i < n; i++ {
		if i == offset {
			fmt.Fprintf(w, "%d ", i)
		} else {
			fmt.Fprintf(w, `<a href="/links/%d/%d">%d</a> `, n, i, i)
		}
	}
	w.Write([]byte("</body></html>"))
}
83938
func (h *Handle) LinkSetVfSpoofchk(link Link, vf int, check bool) error {
	var setting uint32
	base := link.Attrs()
	h.ensureIndex(base)
	req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK)

	msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
	msg.Index = int32(base.Index)
	req.AddData(msg)

	data := nl.NewRtAttr(unix.IFLA_VFINFO_LIST, nil)
	info := data.AddRtAttr(nl.IFLA_VF_INFO, nil)
	if check {
		setting = 1
	}
	vfmsg := nl.VfSpoofchk{
		Vf:      uint32(vf),
		Setting: setting,
	}
	info.AddRtAttr(nl.IFLA_VF_SPOOFCHK, vfmsg.Serialize())
	req.AddData(data)

	_, err := req.Execute(unix.NETLINK_ROUTE, 0)
	return err
}
386382
func (r Response) Links(req *http.Request, baseURL string) (ret jsonapi.Links) {
	ret = make(jsonapi.Links)

	if r.Pagination.Next != nil {
		ret["next"] = buildLink(baseURL, req, r.Pagination.Next)
	}
	if r.Pagination.Prev != nil {
		ret["prev"] = buildLink(baseURL, req, r.Pagination.Prev)
	}
	if r.Pagination.First != nil {
		ret["first"] = buildLink(baseURL, req, r.Pagination.First)
	}
	if r.Pagination.Last != nil {
		ret["last"] = buildLink(baseURL, req, r.Pagination.Last)
	}
	return
}
107227
func httpParseHeaderLine(line []byte) (k, v []byte, ok bool) {
	colon := bytes.IndexByte(line, ':')
	if colon == -1 {
		return
	}

	k = btrim(line[:colon])
	// TODO(gobwas): maybe use just lower here?
	canonicalizeHeaderKey(k)

	v = btrim(line[colon+1:])

	return k, v, true
}
1325105
func LinkSetVfSpoofchk(link Link, vf int, check bool) error {
	return pkgHandle.LinkSetVfSpoofchk(link, vf, check)
}
753420
func (pdoc *tdoc) UsesLink(title string, defParts ...string) htemp.HTML {
	if pdoc.sourcegraphURL == "" {
		return ""
	}

	var def string
	switch len(defParts) {
	case 1:
		// Funcs and types have one def part.
		def = defParts[0]

	case 3:
		// Methods have three def parts, the original receiver name, actual receiver name and method name.
		orig, recv, methodName := defParts[0], defParts[1], defParts[2]

		if orig == "" {
			// TODO: Remove this fallback after 2016-08-05. It's only needed temporarily to backfill data.
			//       Actual receiver is not needed, it's only used because original receiver value
			//       was recently added to gddo/doc package and will be blank until next package rebuild.
			//
			// Use actual receiver as fallback.
			orig = recv
		}

		// Trim "*" from "*T" if it's a pointer receiver method.
		typeName := strings.TrimPrefix(orig, "*")

		def = typeName + "/" + methodName
	default:
		panic(fmt.Errorf("%v defParts, want 1 or 3", len(defParts)))
	}

	q := url.Values{
		"repo": {pdoc.ProjectRoot},
		"pkg":  {pdoc.ImportPath},
		"def":  {def},
	}
	u := pdoc.sourcegraphURL + "/-/godoc/refs?" + q.Encode()
	return htemp.HTML(fmt.Sprintf(`<a class="uses" title="%s" href="%s">Uses</a>`, htemp.HTMLEscapeString(title), htemp.HTMLEscapeString(u)))
}
326390
func ParseCertURI(input *url.URL) (CertURI, error) {
	if input.Scheme != "spiffe" {
		return nil, fmt.Errorf("SPIFFE ID must have 'spiffe' scheme")
	}

	// Path is the raw value of the path without url decoding values.
	// RawPath is empty if there were no encoded values so we must
	// check both.
	path := input.Path
	if input.RawPath != "" {
		path = input.RawPath
	}

	// Test for service IDs
	if v := spiffeIDServiceRegexp.FindStringSubmatch(path); v != nil {
		// Determine the values. We assume they're sane to save cycles,
		// but if the raw path is not empty that means that something is
		// URL encoded so we go to the slow path.
		ns := v[1]
		dc := v[2]
		service := v[3]
		if input.RawPath != "" {
			var err error
			if ns, err = url.PathUnescape(v[1]); err != nil {
				return nil, fmt.Errorf("Invalid namespace: %s", err)
			}
			if dc, err = url.PathUnescape(v[2]); err != nil {
				return nil, fmt.Errorf("Invalid datacenter: %s", err)
			}
			if service, err = url.PathUnescape(v[3]); err != nil {
				return nil, fmt.Errorf("Invalid service: %s", err)
			}
		}

		return &SpiffeIDService{
			Host:       input.Host,
			Namespace:  ns,
			Datacenter: dc,
			Service:    service,
		}, nil
	}

	// Test for signing ID
	if input.Path == "" {
		idx := strings.Index(input.Host, ".")
		if idx > 0 {
			return &SpiffeIDSigning{
				ClusterID: input.Host[:idx],
				Domain:    input.Host[idx+1:],
			}, nil
		}
	}

	return nil, fmt.Errorf("SPIFFE ID is not in the expected format")
}
81166
func crawlTitleFromURL(link string) string {
	_title := strings.Split(link, "/")
	title := strings.Split(_title[4], "-ft-")

	title[0] = strings.Replace(title[0], "-", " ", -1)

	return title[0]
}
811697
func (l Links) Link(rel, href string, args ...interface{}) Links {
	if len(args) != 0 {
		href = fmt.Sprintf(href, args...)
	}

	templated, _ := regexp.Match("{.*?}", []byte(href))

	return l.Add(rel, Link{Href: href, Templated: templated})
}
1235311
func (c ConstantSet) Link(scope Scope, t TypeSpec) (ConstantValue, error) {
	s, ok := RootTypeSpec(t).(*SetSpec)
	if !ok {
		return nil, constantValueCastError{Value: c, Type: t}
	}

	// TODO(abg): Track whether things are linked so that we don't re-link here
	// TODO(abg): Fail for duplicates
	values := make([]ConstantValue, len(c))
	for i, v := range c {
		value, err := v.Link(scope, s.ValueSpec)
		if err != nil {
			return nil, err
		}
		values[i] = value
	}

	return ConstantSet(values), nil
}
112003
func mapToHTTPHeaderHookFunc() mapstructure.DecodeHookFunc {
	return func(
		f reflect.Type,
		t reflect.Type,
		data interface{}) (interface{}, error) {
		if f.Kind() != reflect.Map {
			return data, nil
		}
		if t != reflect.TypeOf(new(http.Header)) {
			return data, nil
		}

		typed, ok := data.(map[string]interface{})
		if !ok {
			return nil, fmt.Errorf("cannot convert %T to http.Header", data)
		}

		n := map[string][]string{}
		for k, v := range typed {
			switch v.(type) {
			case string:
				n[k] = []string{v.(string)}
			case []string:
				n[k] = v.([]string)
			case int, int8, int16, int32, int64:
				n[k] = []string{fmt.Sprintf("%d", v.(int))}
			case float32, float64:
				n[k] = []string{fmt.Sprintf("%f", v.(float64))}
			default:
				return nil, fmt.Errorf("cannot convert %T to http.Header", v)
			}
		}

		return n, nil
	}
}
92327
func ParseMaxAge(header string) int64 {
	if header == "" {
		return -1
	}
	m := maxAgeExp.FindStringSubmatch(header)
	if len(m) == 2 {
		if v, err := strconv.Atoi(m[1]); err == nil {
			return int64(v)
		}
	}
	return -1
}