func (rule *RecordingRule) HTMLSnippet(pathPrefix string) template.HTML {
	ruleExpr := rule.vector.String()
	labels := make(map[string]string, len(rule.labels))
	for _, l := range rule.labels {
		labels[l.Name] = template.HTMLEscapeString(l.Value)
	}

	r := rulefmt.Rule{
		Record: fmt.Sprintf(`<a href="%s">%s</a>`, pathPrefix+strutil.TableLinkForExpression(rule.name), rule.name),
		Expr:   fmt.Sprintf(`<a href="%s">%s</a>`, pathPrefix+strutil.TableLinkForExpression(ruleExpr), template.HTMLEscapeString(ruleExpr)),
		Labels: labels,
	}

	byt, err := yaml.Marshal(r)
	if err != nil {
		return template.HTML(fmt.Sprintf("error marshaling recording rule: %q", template.HTMLEscapeString(err.Error())))
	}

	return template.HTML(byt)
}

func
(
rule
*
RecordingRule
)
HTMLSnippet
(
pathPrefix
string
)
template
.
HTML
{
ruleExpr
:=
rule
.
vector
.
String
(
)
labels
:=
make
(
map
[
string
]
string
,
len
(
rule
.
labels
)
)
for
_
,
l
:=
range
rule
.
labels
{
labels
[
l
.
Name
]
=
template
.
HTMLEscapeString
(
l
.
Value
)
}
r
:=
rulefmt
.
Rule
{
Record
:
fmt
.
Sprintf
(
`<a href="%s">%s</a>`
,
pathPrefix
+
strutil
.
TableLinkForExpression
(
rule
.
name
)
,
rule
.
name
)
,
Expr
:
fmt
.
Sprintf
(
`<a href="%s">%s</a>`
,
pathPrefix
+
strutil
.
TableLinkForExpression
(
ruleExpr
)
,
template
.
HTMLEscapeString
(
ruleExpr
)
)
,
Labels
:
labels
,
}
byt
,
err
:=
yaml
.
Marshal
(
r
)
if
err
!=
{
return
template
.
HTML
(
fmt
.
Sprintf
(
"
"
,
template
.
HTMLEscapeString
(
err
.
Error
(
)
)
)
)
}
return
template
.
HTML
(
byt
)
}

// HTMLSnippet returns an HTML snippet representing this rule.

HTMLSnippet returns an HTML snippet representing this rule .


func (r *ewmaRate) rate() float64 {
	r.mutex.Lock()
	defer r.mutex.Unlock()
	return r.lastRate
}

func ( r * ewmaRate ) rate ( ) float64 { r . mutex . Lock ( ) defer r . mutex . Unlock ( ) return r . lastRate }


func (r *ewmaRate) tick() {
	newEvents := atomic.LoadInt64(&r.newEvents)
	atomic.AddInt64(&r.newEvents, -newEvents)
	instantRate := float64(newEvents) / r.interval.Seconds()

	r.mutex.Lock()
	defer r.mutex.Unlock()

	if r.init {
		r.lastRate += r.alpha * (instantRate - r.lastRate)
	} else {
		r.init = true
		r.lastRate = instantRate
	}
}

func ( r * ewmaRate ) tick ( ) { newEvents := atomic . LoadInt64 ( & r . newEvents ) atomic . AddInt64 ( & r . newEvents , - newEvents ) instantRate := float64 ( newEvents ) / r . interval . Seconds ( ) r . mutex . Lock ( ) defer r . mutex . Unlock ( ) if r . init { r . lastRate += r . alpha * ( instantRate - r . lastRate ) } else { r . init = true r . lastRate = instantRate } }

// tick assumes to be called every r.interval.

tick assumes to be called every r . interval .


func (r *ewmaRate) incr(incr int64) {
	atomic.AddInt64(&r.newEvents, incr)
}

func ( r * ewmaRate ) incr ( incr int64 ) { atomic . AddInt64 ( & r . newEvents , incr ) }


func NewNode(l log.Logger, inf cache.SharedInformer) *Node {
	if l == nil {
		l = log.NewNopLogger()
	}
	n := &Node{logger: l, informer: inf, store: inf.GetStore(), queue: workqueue.NewNamed("node")}
	n.informer.AddEventHandler(cache.ResourceEventHandlerFuncs{
		AddFunc: func(o interface{}) {
			eventCount.WithLabelValues("node", "add").Inc()
			n.enqueue(o)
		},
		DeleteFunc: func(o interface{}) {
			eventCount.WithLabelValues("node", "delete").Inc()
			n.enqueue(o)
		},
		UpdateFunc: func(_, o interface{}) {
			eventCount.WithLabelValues("node", "update").Inc()
			n.enqueue(o)
		},
	})
	return n
}

func NewNode ( l log . Logger , inf cache . SharedInformer ) * Node { if l == nil { l = log . NewNopLogger ( ) } n := & Node { logger : l , informer : inf , store : inf . GetStore ( ) , queue : workqueue . NewNamed ( " " ) } n . informer . AddEventHandler ( cache . ResourceEventHandlerFuncs { AddFunc : func ( o interface { } ) { eventCount . WithLabelValues ( " " , " " ) . Inc ( ) n . enqueue ( o ) } , DeleteFunc : func ( o interface { } ) { eventCount . WithLabelValues ( " " , " " ) . Inc ( ) n . enqueue ( o ) } , UpdateFunc : func ( _ , o interface { } ) { eventCount . WithLabelValues ( " " , " " ) . Inc ( ) n . enqueue ( o ) } , } ) return n }

// NewNode returns a new node discovery.


func CheckConfig(files ...string) int {
	failed := false

	for _, f := range files {
		ruleFiles, err := checkConfig(f)
		if err != nil {
			fmt.Fprintln(os.Stderr, "  FAILED:", err)
			failed = true
		} else {
			fmt.Printf("  SUCCESS: %d rule files found\n", len(ruleFiles))
		}
		fmt.Println()

		for _, rf := range ruleFiles {
			if n, err := checkRules(rf); err != nil {
				fmt.Fprintln(os.Stderr, "  FAILED:", err)
				failed = true
			} else {
				fmt.Printf("  SUCCESS: %d rules found\n", n)
			}
			fmt.Println()
		}
	}
	if failed {
		return 1
	}
	return 0
}

func CheckConfig ( files ... string ) int { failed := false for _ , f := range files { ruleFiles , err := checkConfig ( f ) if err != nil { fmt . Fprintln ( os . Stderr , " " , err ) failed = true } else { fmt . Printf ( " \n " , len ( ruleFiles ) ) } fmt . Println ( ) for _ , rf := range ruleFiles { if n , err := checkRules ( rf ) ; err != nil { fmt . Fprintln ( os . Stderr , " " , err ) failed = true } else { fmt . Printf ( " \n " , n ) } fmt . Println ( ) } } if failed { return 1 } return 0 }

// CheckConfig validates configuration files.

CheckConfig validates configuration files .


func CheckRules(files ...string) int {
	failed := false

	for _, f := range files {
		if n, errs := checkRules(f); errs != nil {
			fmt.Fprintln(os.Stderr, "  FAILED:")
			for _, e := range errs {
				fmt.Fprintln(os.Stderr, e.Error())
			}
			failed = true
		} else {
			fmt.Printf("  SUCCESS: %d rules found\n", n)
		}
		fmt.Println()
	}
	if failed {
		return 1
	}
	return 0
}

func CheckRules ( files ... string ) int { failed := false for _ , f := range files { if n , errs := checkRules ( f ) ; errs != nil { fmt . Fprintln ( os . Stderr , " " ) for _ , e := range errs { fmt . Fprintln ( os . Stderr , e . Error ( ) ) } failed = true } else { fmt . Printf ( " \n " , n ) } fmt . Println ( ) } if failed { return 1 } return 0 }


func CheckMetrics() int {
	l := promlint.New(os.Stdin)
	problems, err := l.Lint()
	if err != nil {
		fmt.Fprintln(os.Stderr, "error while linting:", err)
		return 1
	}

	for _, p := range problems {
		fmt.Fprintln(os.Stderr, p.Metric, p.Text)
	}

	if len(problems) > 0 {
		return 3
	}

	return 0
}

func CheckMetrics ( ) int { l := promlint . New ( os . Stdin ) problems , err := l . Lint ( ) if err != nil { fmt . Fprintln ( os . Stderr , " " , err ) return 1 } for _ , p := range problems { fmt . Fprintln ( os . Stderr , p . Metric , p . Text ) } if len ( problems ) > 0 { return 3 } return 0 }

// CheckMetrics performs a linting pass on input metrics.

CheckMetrics performs a linting pass on input metrics .


func QueryInstant(url, query string, p printer) int {
	config := api.Config{
		Address: url,
	}

	// Create new client.
	c, err := api.NewClient(config)
	if err != nil {
		fmt.Fprintln(os.Stderr, "error creating API client:", err)
		return 1
	}

	// Run query against client.
	api := v1.NewAPI(c)

	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
	val, err := api.Query(ctx, query, time.Now())
	cancel()
	if err != nil {
		fmt.Fprintln(os.Stderr, "query error:", err)
		return 1
	}

	p.printValue(val)

	return 0
}

func
QueryInstant
(
url
,
query
string
,
p
printer
)
int
{
config
:=
api
.
Config
{
Address
:
url
,
}
// Create new client.
c
,
err
:=
api
.
NewClient
(
config
)
if
err
!=
{
fmt
.
Fprintln
(
os
.
Stderr
,
"
"
,
err
)
return
1
}
// Run query against client.
api
:=
v1
.
NewAPI
(
c
)
ctx
,
cancel
:=
context
.
WithTimeout
(
context
.
Background
(
)
,
2
*
time
.
Minute
)
val
,
err
:=
api
.
Query
(
ctx
,
query
,
time
.
Now
(
)
)
cancel
(
)
if
err
!=
{
fmt
.
Fprintln
(
os
.
Stderr
,
"
"
,
err
)
return
1
}
p
.
printValue
(
val
)
return
0
}

// QueryInstant performs an instant query against a Prometheus server.

QueryInstant performs an instant query against a Prometheus server .


func QueryRange(url, query, start, end string, step time.Duration, p printer) int {
	config := api.Config{
		Address: url,
	}

	// Create new client.
	c, err := api.NewClient(config)
	if err != nil {
		fmt.Fprintln(os.Stderr, "error creating API client:", err)
		return 1
	}

	var stime, etime time.Time

	if end == "" {
		etime = time.Now()
	} else {
		etime, err = parseTime(end)
		if err != nil {
			fmt.Fprintln(os.Stderr, "error parsing end time:", err)
			return 1
		}
	}

	if start == "" {
		stime = etime.Add(-5 * time.Minute)
	} else {
		stime, err = parseTime(start)
		if err != nil {
			fmt.Fprintln(os.Stderr, "error parsing start time:", err)
		}
	}

	if !stime.Before(etime) {
		fmt.Fprintln(os.Stderr, "start time is not before end time")
	}

	if step == 0 {
		resolution := math.Max(math.Floor(etime.Sub(stime).Seconds()/250), 1)
		// Convert seconds to nanoseconds such that time.Duration parses correctly.
		step = time.Duration(resolution) * time.Second
	}

	// Run query against client.
	api := v1.NewAPI(c)
	r := v1.Range{Start: stime, End: etime, Step: step}
	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
	val, err := api.QueryRange(ctx, query, r)
	cancel()

	if err != nil {
		fmt.Fprintln(os.Stderr, "query error:", err)
		return 1
	}

	p.printValue(val)
	return 0
}

// QueryRange performs a range query against a Prometheus server.

QueryRange performs a range query against a Prometheus server .


func QuerySeries(url *url.URL, matchers []string, start, end string, p printer) int {
	config := api.Config{
		Address: url.String(),
	}

	// Create new client.
	c, err := api.NewClient(config)
	if err != nil {
		fmt.Fprintln(os.Stderr, "error creating API client:", err)
		return 1
	}

	// TODO: clean up timestamps
	var (
		minTime = time.Now().Add(-9999 * time.Hour)
		maxTime = time.Now().Add(9999 * time.Hour)
	)

	var stime, etime time.Time

	if start == "" {
		stime = minTime
	} else {
		stime, err = parseTime(start)
		if err != nil {
			fmt.Fprintln(os.Stderr, "error parsing start time:", err)
		}
	}

	if end == "" {
		etime = maxTime
	} else {
		etime, err = parseTime(end)
		if err != nil {
			fmt.Fprintln(os.Stderr, "error parsing end time:", err)
		}
	}

	// Run query against client.
	api := v1.NewAPI(c)
	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
	val, err := api.Series(ctx, matchers, stime, etime)
	cancel()

	if err != nil {
		fmt.Fprintln(os.Stderr, "query error:", err)
		return 1
	}

	p.printSeries(val)
	return 0
}

func
QuerySeries
(
url
*
url
.
URL
,
matchers
[
]
string
,
start
,
end
string
,
p
printer
)
int
{
config
:=
api
.
Config
{
Address
:
url
.
String
(
)
,
}
// Create new client.
c
,
err
:=
api
.
NewClient
(
config
)
if
err
!=
{
fmt
.
Fprintln
(
os
.
Stderr
,
"
"
,
err
)
return
1
}
// TODO: clean up timestamps
var
(
minTime
=
time
.
Now
(
)
.
Add
(
9999
*
time
.
Hour
)
maxTime
=
time
.
Now
(
)
.
Add
(
9999
*
time
.
Hour
)
)
var
stime
,
etime
time
.
Time
if
start
==
"
"
{
stime
=
minTime
}
else
{
stime
,
err
=
parseTime
(
start
)
if
err
!=
{
fmt
.
Fprintln
(
os
.
Stderr
,
"
"
,
err
)
}
}
if
end
==
"
"
{
etime
=
maxTime
}
else
{
etime
,
err
=
parseTime
(
end
)
if
err
!=
{
fmt
.
Fprintln
(
os
.
Stderr
,
"
"
,
err
)
}
}
// Run query against client.
api
:=
v1
.
NewAPI
(
c
)
ctx
,
cancel
:=
context
.
WithTimeout
(
context
.
Background
(
)
,
2
*
time
.
Minute
)
val
,
err
:=
api
.
Series
(
ctx
,
matchers
,
stime
,
etime
)
cancel
(
)
if
err
!=
{
fmt
.
Fprintln
(
os
.
Stderr
,
"
"
,
err
)
return
1
}
p
.
printSeries
(
val
)
return
0
}

// QuerySeries queries for a series against a Prometheus server.

QuerySeries queries for a series against a Prometheus server .


func QueryLabels(url *url.URL, name string, p printer) int {
	config := api.Config{
		Address: url.String(),
	}

	// Create new client.
	c, err := api.NewClient(config)
	if err != nil {
		fmt.Fprintln(os.Stderr, "error creating API client:", err)
		return 1
	}

	// Run query against client.
	api := v1.NewAPI(c)
	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
	val, err := api.LabelValues(ctx, name)
	cancel()

	if err != nil {
		fmt.Fprintln(os.Stderr, "query error:", err)
		return 1
	}

	p.printLabelValues(val)
	return 0
}

func
QueryLabels
(
url
*
url
.
URL
,
name
string
,
p
printer
)
int
{
config
:=
api
.
Config
{
Address
:
url
.
String
(
)
,
}
// Create new client.
c
,
err
:=
api
.
NewClient
(
config
)
if
err
!=
{
fmt
.
Fprintln
(
os
.
Stderr
,
"
"
,
err
)
return
1
}
// Run query against client.
api
:=
v1
.
NewAPI
(
c
)
ctx
,
cancel
:=
context
.
WithTimeout
(
context
.
Background
(
)
,
2
*
time
.
Minute
)
val
,
err
:=
api
.
LabelValues
(
ctx
,
name
)
cancel
(
)
if
err
!=
{
fmt
.
Fprintln
(
os
.
Stderr
,
"
"
,
err
)
return
1
}
p
.
printLabelValues
(
val
)
return
0
}

// QueryLabels queries for label values against a Prometheus server.

QueryLabels queries for label values against a Prometheus server .


func (tg *Group) UnmarshalJSON(b []byte) error {
	g := struct {
		Targets []string       `json:"targets"`
		Labels  model.LabelSet `json:"labels"`
	}{}

	dec := json.NewDecoder(bytes.NewReader(b))
	dec.DisallowUnknownFields()
	if err := dec.Decode(&g); err != nil {
		return err
	}
	tg.Targets = make([]model.LabelSet, 0, len(g.Targets))
	for _, t := range g.Targets {
		tg.Targets = append(tg.Targets, model.LabelSet{
			model.AddressLabel: model.LabelValue(t),
		})
	}
	tg.Labels = g.Labels
	return nil
}

func ( tg * Group ) UnmarshalJSON ( b [ ] byte ) error { g := struct { Targets [ ] string `json:"targets"` Labels model . LabelSet `json:"labels"` } { } dec := json . NewDecoder ( bytes . NewReader ( b ) ) dec . DisallowUnknownFields ( ) if err := dec . Decode ( & g ) ; err != nil { return err } tg . Targets = make ( [ ] model . LabelSet , 0 , len ( g . Targets ) ) for _ , t := range g . Targets { tg . Targets = append ( tg . Targets , model . LabelSet { model . AddressLabel : model . LabelValue ( t ) , } ) } tg . Labels = g . Labels return nil }

// UnmarshalJSON implements the json.Unmarshaler interface.

UnmarshalJSON implements the json . Unmarshaler interface .


func NewStreamReader(sw StreamWriter) io.ReadCloser {
	pc := fasthttputil.NewPipeConns()
	pw := pc.Conn1()
	pr := pc.Conn2()

	var bw *bufio.Writer
	v := streamWriterBufPool.Get()
	if v == nil {
		bw = bufio.NewWriter(pw)
	} else {
		bw = v.(*bufio.Writer)
		bw.Reset(pw)
	}

	go func() {
		sw(bw)
		bw.Flush()
		pw.Close()

		streamWriterBufPool.Put(bw)
	}()

	return pr
}

func NewStreamReader ( sw StreamWriter ) io . ReadCloser { pc := fasthttputil . NewPipeConns ( ) pw := pc . Conn1 ( ) pr := pc . Conn2 ( ) var bw * bufio . Writer v := streamWriterBufPool . Get ( ) if v == nil { bw = bufio . NewWriter ( pw ) } else { bw = v . ( * bufio . Writer ) bw . Reset ( pw ) } go func ( ) { sw ( bw ) bw . Flush ( ) pw . Close ( ) streamWriterBufPool . Put ( bw ) } ( ) return pr }

// NewStreamReader returns a reader, which replays all the data generated by sw.
//
// The returned reader may be passed to Response.SetBodyStream.
//
// Close must be called on the returned reader after all the required data
// has been read. Otherwise goroutine leak may occur.
//
// See also Response.SetBodyStreamWriter.

NewStreamReader returns a reader which replays all the data generated by sw . The returned reader may be passed to Response . SetBodyStream . Close must be called on the returned reader after all the required data has been read . Otherwise goroutine leak may occur . See also Response . SetBodyStreamWriter .


func StatusMessage(statusCode int) string {
	s := statusMessages[statusCode]
	if s == "" {
		s = "Unknown Status Code"
	}
	return s
}

func StatusMessage ( statusCode int ) string { s := statusMessages [ statusCode ] if s == " " { s = " " } return s }

// StatusMessage returns HTTP status message for the given status code.

StatusMessage returns HTTP status message for the given status code .


func (a *Args) CopyTo(dst *Args) {
	dst.Reset()
	dst.args = copyArgs(dst.args, a.args)
}

func ( a * Args ) CopyTo ( dst * Args ) { dst . Reset ( ) dst . args = copyArgs ( dst . args , a . args ) }


func (a *Args) Parse(s string) {
	a.buf = append(a.buf[:0], s...)
	a.ParseBytes(a.buf)
}

func ( a * Args ) Parse ( s string ) { a . buf = append ( a . buf [ : 0 ] , s ... ) a . ParseBytes ( a . buf ) }

// Parse parses the given string containing query args.

Parse parses the given string containing query args .


func (a *Args) ParseBytes(b []byte) {
	a.Reset()

	var s argsScanner
	s.b = b

	var kv *argsKV
	a.args, kv = allocArg(a.args)
	for s.next(kv) {
		if len(kv.key) > 0 || len(kv.value) > 0 {
			a.args, kv = allocArg(a.args)
		}
	}
	a.args = releaseArg(a.args)
}

func ( a * Args ) ParseBytes ( b [ ] byte ) { a . Reset ( ) var s argsScanner s . b = b var kv * argsKV a . args , kv = allocArg ( a . args ) for s . next ( kv ) { if len ( kv . key ) > 0 || len ( kv . value ) > 0 { a . args , kv = allocArg ( a . args ) } } a . args = releaseArg ( a . args ) }

// ParseBytes parses the given b containing query args.

ParseBytes parses the given b containing query args .


func (a *Args) QueryString() []byte {
	a.buf = a.AppendBytes(a.buf[:0])
	return a.buf
}

func ( a * Args ) QueryString ( ) [ ] byte { a . buf = a . AppendBytes ( a . buf [ : 0 ] ) return a . buf }

// QueryString returns query string for the args.
//
// The returned value is valid until the next call to Args methods.

QueryString returns query string for the args . The returned value is valid until the next call to Args methods .


func (a *Args) AppendBytes(dst []byte) []byte {
	for i, n := 0, len(a.args); i < n; i++ {
		kv := &a.args[i]
		dst = AppendQuotedArg(dst, kv.key)
		if !kv.noValue {
			dst = append(dst, '=')
			if len(kv.value) > 0 {
				dst = AppendQuotedArg(dst, kv.value)
			}
		}
		if i+1 < n {
			dst = append(dst, '&')
		}
	}
	return dst
}

func ( a * Args ) AppendBytes ( dst [ ] byte ) [ ] byte { for i , n := 0 , len ( a . args ) ; i < n ; i ++ { kv := & a . args [ i ] dst = AppendQuotedArg ( dst , kv . key ) if ! kv . noValue { dst = append ( dst , '=' ) if len ( kv . value ) > 0 { dst = AppendQuotedArg ( dst , kv . value ) } } if i + 1 < n { dst = append ( dst , '&' ) } } return dst }

// AppendBytes appends query string to dst and returns the extended dst.

AppendBytes appends query string to dst and returns the extended dst .


func (a *Args) WriteTo(w io.Writer) (int64, error) {
	n, err := w.Write(a.QueryString())
	return int64(n), err
}

func ( a * Args ) WriteTo ( w io . Writer ) ( int64 , error ) { n , err := w . Write ( a . QueryString ( ) ) return int64 ( n ) , err }

// WriteTo writes query string to w.
//
// WriteTo implements io.WriterTo interface.

WriteTo writes query string to w . WriteTo implements io . WriterTo interface .


func (a *Args) Del(key string) {
	a.args = delAllArgs(a.args, key)
}

func ( a * Args ) Del ( key string ) { a . args = delAllArgs ( a . args , key ) }

// Del deletes argument with the given key from query args.

Del deletes argument with the given key from query args .


func (a *Args) DelBytes(key []byte) {
	a.args = delAllArgs(a.args, b2s(key))
}

func ( a * Args ) DelBytes ( key [ ] byte ) { a . args = delAllArgs ( a . args , b2s ( key ) ) }

// DelBytes deletes argument with the given key from query args.

DelBytes deletes argument with the given key from query args .


func (a *Args) Add(key, value string) {
	a.args = appendArg(a.args, key, value, argsHasValue)
}

func ( a * Args ) Add ( key , value string ) { a . args = appendArg ( a . args , key , value , argsHasValue ) }

// Add adds 'key=value' argument.
//
// Multiple values for the same key may be added.

Add adds key = value argument . Multiple values for the same key may be added .


func (a *Args) AddBytesK(key []byte, value string) {
	a.args = appendArg(a.args, b2s(key), value, argsHasValue)
}

func ( a * Args ) AddBytesK ( key [ ] byte , value string ) { a . args = appendArg ( a . args , b2s ( key ) , value , argsHasValue ) }

// AddBytesK adds 'key=value' argument.
//
// Multiple values for the same key may be added.

AddBytesK adds key = value argument . Multiple values for the same key may be added .


func (a *Args) AddBytesKV(key, value []byte) {
	a.args = appendArg(a.args, b2s(key), b2s(value), argsHasValue)
}

func ( a * Args ) AddBytesKV ( key , value [ ] byte ) { a . args = appendArg ( a . args , b2s ( key ) , b2s ( value ) , argsHasValue ) }

// AddBytesKV adds 'key=value' argument.
//
// Multiple values for the same key may be added.

AddBytesKV adds key = value argument . Multiple values for the same key may be added .


func (a *Args) AddNoValue(key string) {
	a.args = appendArg(a.args, key, "", argsNoValue)
}

func ( a * Args ) AddNoValue ( key string ) { a . args = appendArg ( a . args , key , " " , argsNoValue ) }

// AddNoValue adds only 'key' as argument without the '='.
//
// Multiple values for the same key may be added.

AddNoValue adds only key as argument without the = . Multiple values for the same key may be added .


func (a *Args) AddBytesKNoValue(key []byte) {
	a.args = appendArg(a.args, b2s(key), "", argsNoValue)
}

func ( a * Args ) AddBytesKNoValue ( key [ ] byte ) { a . args = appendArg ( a . args , b2s ( key ) , " " , argsNoValue ) }

// AddBytesKNoValue adds only 'key' as argument without the '='.
//
// Multiple values for the same key may be added.

AddBytesKNoValue adds only key as argument without the = . Multiple values for the same key may be added .


func (a *Args) Set(key, value string) {
	a.args = setArg(a.args, key, value, argsHasValue)
}

func ( a * Args ) Set ( key , value string ) { a . args = setArg ( a . args , key , value , argsHasValue ) }


func (a *Args) SetBytesV(key string, value []byte) {
	a.args = setArg(a.args, key, b2s(value), argsHasValue)
}

func ( a * Args ) SetBytesV ( key string , value [ ] byte ) { a . args = setArg ( a . args , key , b2s ( value ) , argsHasValue ) }


func (a *Args) SetBytesKV(key, value []byte) {
	a.args = setArgBytes(a.args, key, value, argsHasValue)
}

func ( a * Args ) SetBytesKV ( key , value [ ] byte ) { a . args = setArgBytes ( a . args , key , value , argsHasValue ) }

// SetBytesKV sets 'key=value' argument.


func (a *Args) SetNoValue(key string) {
	a.args = setArg(a.args, key, "", argsNoValue)
}

func ( a * Args ) SetNoValue ( key string ) { a . args = setArg ( a . args , key , " " , argsNoValue ) }

// SetNoValue sets only 'key' as argument without the '='.
//
// Only key in argumemt, like key1&key2

SetNoValue sets only key as argument without the = . Only key in argumemt like key1&key2


func (a *Args) SetBytesKNoValue(key []byte) {
	a.args = setArg(a.args, b2s(key), "", argsNoValue)
}

func ( a * Args ) SetBytesKNoValue ( key [ ] byte ) { a . args = setArg ( a . args , b2s ( key ) , " " , argsNoValue ) }

// SetBytesKNoValue sets 'key' argument.


func (a *Args) Peek(key string) []byte {
	return peekArgStr(a.args, key)
}

func ( a * Args ) Peek ( key string ) [ ] byte { return peekArgStr ( a . args , key ) }

// Peek returns query arg value for the given key.
//
// Returned value is valid until the next Args call.

Peek returns query arg value for the given key . Returned value is valid until the next Args call .


func (a *Args) PeekBytes(key []byte) []byte {
	return peekArgBytes(a.args, key)
}

func ( a * Args ) PeekBytes ( key [ ] byte ) [ ] byte { return peekArgBytes ( a . args , key ) }

// PeekBytes returns query arg value for the given key.
//
// Returned value is valid until the next Args call.

PeekBytes returns query arg value for the given key . Returned value is valid until the next Args call .


func (a *Args) PeekMulti(key string) [][]byte {
	var values [][]byte
	a.VisitAll(func(k, v []byte) {
		if string(k) == key {
			values = append(values, v)
		}
	})
	return values
}

func ( a * Args ) PeekMulti ( key string ) [ ] [ ] byte { var values [ ] [ ] byte a . VisitAll ( func ( k , v [ ] byte ) { if string ( k ) == key { values = append ( values , v ) } } ) return values }

// PeekMulti returns all the arg values for the given key.

PeekMulti returns all the arg values for the given key .


func (a *Args) PeekMultiBytes(key []byte) [][]byte {
	return a.PeekMulti(b2s(key))
}

func ( a * Args ) PeekMultiBytes ( key [ ] byte ) [ ] [ ] byte { return a . PeekMulti ( b2s ( key ) ) }

// PeekMultiBytes returns all the arg values for the given key.

PeekMultiBytes returns all the arg values for the given key .


func (a *Args) Has(key string) bool {
	return hasArg(a.args, key)
}

func ( a * Args ) Has ( key string ) bool { return hasArg ( a . args , key ) }

// Has returns true if the given key exists in Args.

Has returns true if the given key exists in Args .


func (a *Args) HasBytes(key []byte) bool {
	return hasArg(a.args, b2s(key))
}

func ( a * Args ) HasBytes ( key [ ] byte ) bool { return hasArg ( a . args , b2s ( key ) ) }

// HasBytes returns true if the given key exists in Args.

HasBytes returns true if the given key exists in Args .


func (a *Args) GetUint(key string) (int, error) {
	value := a.Peek(key)
	if len(value) == 0 {
		return -1, ErrNoArgValue
	}
	return ParseUint(value)
}

func ( a * Args ) GetUint ( key string ) ( int , error ) { value := a . Peek ( key ) if len ( value ) == 0 { return - 1 , ErrNoArgValue } return ParseUint ( value ) }

// GetUint returns uint value for the given key.

GetUint returns uint value for the given key .


func (a *Args) SetUint(key string, value int) {
	bb := bytebufferpool.Get()
	bb.B = AppendUint(bb.B[:0], value)
	a.SetBytesV(key, bb.B)
	bytebufferpool.Put(bb)
}

func ( a * Args ) SetUint ( key string , value int ) { bb := bytebufferpool . Get ( ) bb . B = AppendUint ( bb . B [ : 0 ] , value ) a . SetBytesV ( key , bb . B ) bytebufferpool . Put ( bb ) }

// SetUint sets uint value for the given key.

SetUint sets uint value for the given key .


func (a *Args) SetUintBytes(key []byte, value int) {
	a.SetUint(b2s(key), value)
}

func ( a * Args ) SetUintBytes ( key [ ] byte , value int ) { a . SetUint ( b2s ( key ) , value ) }

// SetUintBytes sets uint value for the given key.

SetUintBytes sets uint value for the given key .


func (a *Args) GetUfloat(key string) (float64, error) {
	value := a.Peek(key)
	if len(value) == 0 {
		return -1, ErrNoArgValue
	}
	return ParseUfloat(value)
}

func ( a * Args ) GetUfloat ( key string ) ( float64 , error ) { value := a . Peek ( key ) if len ( value ) == 0 { return - 1 , ErrNoArgValue } return ParseUfloat ( value ) }

// GetUfloat returns ufloat value for the given key.

GetUfloat returns ufloat value for the given key .


func (a *Args) GetBool(key string) bool {
	switch b2s(a.Peek(key)) {
	// Support the same true cases as strconv.ParseBool
	// See: https://github.com/golang/go/blob/4e1b11e2c9bdb0ddea1141eed487be1a626ff5be/src/strconv/atob.go#L12
	// and Y and Yes versions.
	case "1", "t", "T", "true", "TRUE", "True", "y", "yes", "Y", "YES", "Yes":
		return true
	default:
		return false
	}
}

// GetBool returns boolean value for the given key.
//
// true is returned for "1", "t", "T", "true", "TRUE", "True", "y", "yes", "Y", "YES", "Yes",
// otherwise false is returned.

GetBool returns boolean value for the given key . true is returned for 1 t T true TRUE True y yes Y YES Yes otherwise false is returned .


func decodeArgAppendNoPlus(dst, src []byte) []byte {
	if bytes.IndexByte(src, '%') < 0 {
		// fast path: src doesn't contain encoded chars
		return append(dst, src...)
	}

	// slow path
	for i := 0; i < len(src); i++ {
		c := src[i]
		if c == '%' {
			if i+2 >= len(src) {
				return append(dst, src[i:]...)
			}
			x2 := hex2intTable[src[i+2]]
			x1 := hex2intTable[src[i+1]]
			if x1 == 16 || x2 == 16 {
				dst = append(dst, '%')
			} else {
				dst = append(dst, x1<<4|x2)
				i += 2
			}
		} else {
			dst = append(dst, c)
		}
	}
	return dst
}

// decodeArgAppendNoPlus is almost identical to decodeArgAppend, but it doesn't
// substitute '+' with ' '.
//
// The function is copy-pasted from decodeArgAppend due to the performance
// reasons only.

decodeArgAppendNoPlus is almost identical to decodeArgAppend but it doesn t substitute + with . The function is copy - pasted from decodeArgAppend due to the performance reasons only .


func AppendHTMLEscape(dst []byte, s string) []byte {
	if strings.IndexByte(s, '<') < 0 &&
		strings.IndexByte(s, '>') < 0 &&
		strings.IndexByte(s, '"') < 0 &&
		strings.IndexByte(s, '\'') < 0 {

		// fast path - nothing to escape
		return append(dst, s...)
	}

	// slow path
	var prev int
	var sub string
	for i, n := 0, len(s); i < n; i++ {
		sub = ""
		switch s[i] {
		case '<':
			sub = "<"
		case '>':
			sub = ">"
		case '"':
			sub = """
		case '\'':
			sub = "'"
		}
		if len(sub) > 0 {
			dst = append(dst, s[prev:i]...)
			dst = append(dst, sub...)
			prev = i + 1
		}
	}
	return append(dst, s[prev:]...)
}

func
AppendHTMLEscape
(
dst
[
]
byte
,
s
string
)
[
]
byte
{
if
strings
.
IndexByte
(
s
,
'<'
)
<
0
&&
strings
.
IndexByte
(
s
,
'>'
)
<
0
&&
strings
.
IndexByte
(
s
,
'"'
)
<
0
&&
strings
.
IndexByte
(
s
,
'\''
)
<
0
{
// fast path - nothing to escape
return
append
(
dst
,
s
...
)
}
// slow path
var
prev
int
var
sub
string
for
i
,
n
:=
0
,
len
(
s
)
;
i
<
n
;
i
++
{
sub
=
"
"
switch
s
[
i
]
{
case
'<'
:
sub
=
"
"
case
'>'
:
sub
=
"
"
case
'"'
:
sub
=
"
"
case
'\''
:
sub
=
"
"
}
if
len
(
sub
)
>
0
{
dst
=
append
(
dst
,
s
[
prev
:
i
]
...
)
dst
=
append
(
dst
,
sub
...
)
prev
=
i
+
1
}
}
return
append
(
dst
,
s
[
prev
:
]
...
)
}

// AppendHTMLEscape appends html-escaped s to dst and returns the extended dst.

AppendHTMLEscape appends html - escaped s to dst and returns the extended dst .


func AppendIPv4(dst []byte, ip net.IP) []byte {
	ip = ip.To4()
	if ip == nil {
		return append(dst, "non-v4 ip passed to AppendIPv4"...)
	}

	dst = AppendUint(dst, int(ip[0]))
	for i := 1; i < 4; i++ {
		dst = append(dst, '.')
		dst = AppendUint(dst, int(ip[i]))
	}
	return dst
}

func AppendIPv4 ( dst [ ] byte , ip net . IP ) [ ] byte { ip = ip . To4 ( ) if ip == nil { return append ( dst , " " ... ) } dst = AppendUint ( dst , int ( ip [ 0 ] ) ) for i := 1 ; i < 4 ; i ++ { dst = append ( dst , '.' ) dst = AppendUint ( dst , int ( ip [ i ] ) ) } return dst }

// AppendIPv4 appends string representation of the given ip v4 to dst
// and returns the extended dst.

AppendIPv4 appends string representation of the given ip v4 to dst and returns the extended dst .


func ParseIPv4(dst net.IP, ipStr []byte) (net.IP, error) {
	if len(ipStr) == 0 {
		return dst, errEmptyIPStr
	}
	if len(dst) < net.IPv4len {
		dst = make([]byte, net.IPv4len)
	}
	copy(dst, net.IPv4zero)
	dst = dst.To4()
	if dst == nil {
		panic("BUG: dst must not be nil")
	}

	b := ipStr
	for i := 0; i < 3; i++ {
		n := bytes.IndexByte(b, '.')
		if n < 0 {
			return dst, fmt.Errorf("cannot find dot in ipStr %q", ipStr)
		}
		v, err := ParseUint(b[:n])
		if err != nil {
			return dst, fmt.Errorf("cannot parse ipStr %q: %s", ipStr, err)
		}
		if v > 255 {
			return dst, fmt.Errorf("cannot parse ipStr %q: ip part cannot exceed 255: parsed %d", ipStr, v)
		}
		dst[i] = byte(v)
		b = b[n+1:]
	}
	v, err := ParseUint(b)
	if err != nil {
		return dst, fmt.Errorf("cannot parse ipStr %q: %s", ipStr, err)
	}
	if v > 255 {
		return dst, fmt.Errorf("cannot parse ipStr %q: ip part cannot exceed 255: parsed %d", ipStr, v)
	}
	dst[3] = byte(v)

	return dst, nil
}

func ParseIPv4 ( dst net . IP , ipStr [ ] byte ) ( net . IP , error ) { if len ( ipStr ) == 0 { return dst , errEmptyIPStr } if len ( dst ) < net . IPv4len { dst = make ( [ ] byte , net . IPv4len ) } copy ( dst , net . IPv4zero ) dst = dst . To4 ( ) if dst == nil { panic ( " " ) } b := ipStr for i := 0 ; i < 3 ; i ++ { n := bytes . IndexByte ( b , '.' ) if n < 0 { return dst , fmt . Errorf ( " " , ipStr ) } v , err := ParseUint ( b [ : n ] ) if err != nil { return dst , fmt . Errorf ( " " , ipStr , err ) } if v > 255 { return dst , fmt . Errorf ( " " , ipStr , v ) } dst [ i ] = byte ( v ) b = b [ n + 1 : ] } v , err := ParseUint ( b ) if err != nil { return dst , fmt . Errorf ( " " , ipStr , err ) } if v > 255 { return dst , fmt . Errorf ( " " , ipStr , v ) } dst [ 3 ] = byte ( v ) return dst , nil }

// ParseIPv4 parses ip address from ipStr into dst and returns the extended dst.

ParseIPv4 parses ip address from ipStr into dst and returns the extended dst .


func ParseUint(buf []byte) (int, error) {
	v, n, err := parseUintBuf(buf)
	if n != len(buf) {
		return -1, errUnexpectedTrailingChar
	}
	return v, err
}

func ParseUint ( buf [ ] byte ) ( int , error ) { v , n , err := parseUintBuf ( buf ) if n != len ( buf ) { return - 1 , errUnexpectedTrailingChar } return v , err }


func ParseUfloat(buf []byte) (float64, error) {
	if len(buf) == 0 {
		return -1, errEmptyFloat
	}
	b := buf
	var v uint64
	var offset = 1.0
	var pointFound bool
	for i, c := range b {
		if c < '0' || c > '9' {
			if c == '.' {
				if pointFound {
					return -1, errDuplicateFloatPoint
				}
				pointFound = true
				continue
			}
			if c == 'e' || c == 'E' {
				if i+1 >= len(b) {
					return -1, errUnexpectedFloatEnd
				}
				b = b[i+1:]
				minus := -1
				switch b[0] {
				case '+':
					b = b[1:]
					minus = 1
				case '-':
					b = b[1:]
				default:
					minus = 1
				}
				vv, err := ParseUint(b)
				if err != nil {
					return -1, errInvalidFloatExponent
				}
				return float64(v) * offset * math.Pow10(minus*int(vv)), nil
			}
			return -1, errUnexpectedFloatChar
		}
		v = 10*v + uint64(c-'0')
		if pointFound {
			offset /= 10
		}
	}
	return float64(v) * offset, nil
}

func ParseUfloat ( buf [ ] byte ) ( float64 , error ) { if len ( buf ) == 0 { return - 1 , errEmptyFloat } b := buf var v uint64 var offset = 1.0 var pointFound bool for i , c := range b { if c < '0' || c > '9' { if c == '.' { if pointFound { return - 1 , errDuplicateFloatPoint } pointFound = true continue } if c == 'e' || c == 'E' { if i + 1 >= len ( b ) { return - 1 , errUnexpectedFloatEnd } b = b [ i + 1 : ] minus := - 1 switch b [ 0 ] { case '+' : b = b [ 1 : ] minus = 1 case '-' : b = b [ 1 : ] default : minus = 1 } vv , err := ParseUint ( b ) if err != nil { return - 1 , errInvalidFloatExponent } return float64 ( v ) * offset * math . Pow10 ( minus * int ( vv ) ) , nil } return - 1 , errUnexpectedFloatChar } v = 10 * v + uint64 ( c - '0' ) if pointFound { offset /= 10 } } return float64 ( v ) * offset , nil }

// ParseUfloat parses unsigned float from buf.

ParseUfloat parses unsigned float from buf .


func AppendQuotedArg(dst, src []byte) []byte {
	for _, c := range src {
		// See http://www.w3.org/TR/html5/forms.html#form-submission-algorithm
		if c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' ||
			c == '*' || c == '-' || c == '.' || c == '_' {
			dst = append(dst, c)
		} else {
			dst = append(dst, '%', hexCharUpper(c>>4), hexCharUpper(c&15))
		}
	}
	return dst
}

// AppendQuotedArg appends url-encoded src to dst and returns appended dst.

AppendQuotedArg appends url - encoded src to dst and returns appended dst .


func (u *URI) CopyTo(dst *URI) {
	dst.Reset()
	dst.pathOriginal = append(dst.pathOriginal[:0], u.pathOriginal...)
	dst.scheme = append(dst.scheme[:0], u.scheme...)
	dst.path = append(dst.path[:0], u.path...)
	dst.queryString = append(dst.queryString[:0], u.queryString...)
	dst.hash = append(dst.hash[:0], u.hash...)
	dst.host = append(dst.host[:0], u.host...)

	u.queryArgs.CopyTo(&dst.queryArgs)
	dst.parsedQueryArgs = u.parsedQueryArgs

	// fullURI and requestURI shouldn't be copied, since they are created
	// from scratch on each FullURI() and RequestURI() call.
	dst.h = u.h
}


func (u *URI) SetHash(hash string) {
	u.hash = append(u.hash[:0], hash...)
}

func ( u * URI ) SetHash ( hash string ) { u . hash = append ( u . hash [ : 0 ] , hash ... ) }


func (u *URI) SetHashBytes(hash []byte) {
	u.hash = append(u.hash[:0], hash...)
}

func ( u * URI ) SetHashBytes ( hash [ ] byte ) { u . hash = append ( u . hash [ : 0 ] , hash ... ) }


func (u *URI) SetQueryString(queryString string) {
	u.queryString = append(u.queryString[:0], queryString...)
	u.parsedQueryArgs = false
}

func ( u * URI ) SetQueryString ( queryString string ) { u . queryString = append ( u . queryString [ : 0 ] , queryString ... ) u . parsedQueryArgs = false }

// SetQueryString sets URI query string.


func (u *URI) SetQueryStringBytes(queryString []byte) {
	u.queryString = append(u.queryString[:0], queryString...)
	u.parsedQueryArgs = false
}

func ( u * URI ) SetQueryStringBytes ( queryString [ ] byte ) { u . queryString = append ( u . queryString [ : 0 ] , queryString ... ) u . parsedQueryArgs = false }

// SetQueryStringBytes sets URI query string.

SetQueryStringBytes sets URI query string .


func (u *URI) SetPath(path string) {
	u.pathOriginal = append(u.pathOriginal[:0], path...)
	u.path = normalizePath(u.path, u.pathOriginal)
}

func ( u * URI ) SetPath ( path string ) { u . pathOriginal = append ( u . pathOriginal [ : 0 ] , path ... ) u . path = normalizePath ( u . path , u . pathOriginal ) }


func (u *URI) SetPathBytes(path []byte) {
	u.pathOriginal = append(u.pathOriginal[:0], path...)
	u.path = normalizePath(u.path, u.pathOriginal)
}

func ( u * URI ) SetPathBytes ( path [ ] byte ) { u . pathOriginal = append ( u . pathOriginal [ : 0 ] , path ... ) u . path = normalizePath ( u . path , u . pathOriginal ) }


func (u *URI) SetScheme(scheme string) {
	u.scheme = append(u.scheme[:0], scheme...)
	lowercaseBytes(u.scheme)
}

func ( u * URI ) SetScheme ( scheme string ) { u . scheme = append ( u . scheme [ : 0 ] , scheme ... ) lowercaseBytes ( u . scheme ) }

// SetScheme sets URI scheme, i.e. http, https, ftp, etc.

SetScheme sets URI scheme i . e . http https ftp etc .


func (u *URI) SetSchemeBytes(scheme []byte) {
	u.scheme = append(u.scheme[:0], scheme...)
	lowercaseBytes(u.scheme)
}

func ( u * URI ) SetSchemeBytes ( scheme [ ] byte ) { u . scheme = append ( u . scheme [ : 0 ] , scheme ... ) lowercaseBytes ( u . scheme ) }

// SetSchemeBytes sets URI scheme, i.e. http, https, ftp, etc.

SetSchemeBytes sets URI scheme i . e . http https ftp etc .


func (u *URI) Reset() {
	u.pathOriginal = u.pathOriginal[:0]
	u.scheme = u.scheme[:0]
	u.path = u.path[:0]
	u.queryString = u.queryString[:0]
	u.hash = u.hash[:0]

	u.host = u.host[:0]
	u.queryArgs.Reset()
	u.parsedQueryArgs = false

	// There is no need in u.fullURI = u.fullURI[:0], since full uri
	// is calculated on each call to FullURI().

	// There is no need in u.requestURI = u.requestURI[:0], since requestURI
	// is calculated on each call to RequestURI().

	u.h = nil
}


func (u *URI) SetHost(host string) {
	u.host = append(u.host[:0], host...)
	lowercaseBytes(u.host)
}

func ( u * URI ) SetHost ( host string ) { u . host = append ( u . host [ : 0 ] , host ... ) lowercaseBytes ( u . host ) }


func (u *URI) SetHostBytes(host []byte) {
	u.host = append(u.host[:0], host...)
	lowercaseBytes(u.host)
}

func ( u * URI ) SetHostBytes ( host [ ] byte ) { u . host = append ( u . host [ : 0 ] , host ... ) lowercaseBytes ( u . host ) }


func (u *URI) RequestURI() []byte {
	dst := appendQuotedPath(u.requestURI[:0], u.Path())
	if u.queryArgs.Len() > 0 {
		dst = append(dst, '?')
		dst = u.queryArgs.AppendBytes(dst)
	} else if len(u.queryString) > 0 {
		dst = append(dst, '?')
		dst = append(dst, u.queryString...)
	}
	if len(u.hash) > 0 {
		dst = append(dst, '#')
		dst = append(dst, u.hash...)
	}
	u.requestURI = dst
	return u.requestURI
}

func ( u * URI ) RequestURI ( ) [ ] byte { dst := appendQuotedPath ( u . requestURI [ : 0 ] , u . Path ( ) ) if u . queryArgs . Len ( ) > 0 { dst = append ( dst , '?' ) dst = u . queryArgs . AppendBytes ( dst ) } else if len ( u . queryString ) > 0 { dst = append ( dst , '?' ) dst = append ( dst , u . queryString ... ) } if len ( u . hash ) > 0 { dst = append ( dst , '#' ) dst = append ( dst , u . hash ... ) } u . requestURI = dst return u . requestURI }

// RequestURI returns RequestURI - i.e. URI without Scheme and Host.

RequestURI returns RequestURI - i . e . URI without Scheme and Host .


func (u *URI) AppendBytes(dst []byte) []byte {
	dst = u.appendSchemeHost(dst)
	return append(dst, u.RequestURI()...)
}

func ( u * URI ) AppendBytes ( dst [ ] byte ) [ ] byte { dst = u . appendSchemeHost ( dst ) return append ( dst , u . RequestURI ( ) ... ) }

// AppendBytes appends full uri to dst and returns the extended dst.

AppendBytes appends full uri to dst and returns the extended dst .


func (u *URI) WriteTo(w io.Writer) (int64, error) {
	n, err := w.Write(u.FullURI())
	return int64(n), err
}

func ( u * URI ) WriteTo ( w io . Writer ) ( int64 , error ) { n , err := w . Write ( u . FullURI ( ) ) return int64 ( n ) , err }

// WriteTo writes full uri to w.
//
// WriteTo implements io.WriterTo interface.

WriteTo writes full uri to w . WriteTo implements io . WriterTo interface .


func NewWriter(dstW io.Writer, newWriter NewWriterFunc) Writer {
	w := &writer{
		dstW: dstW,
	}
	w.zw = newWriter(&w.xw)
	return w
}

func NewWriter ( dstW io . Writer , newWriter NewWriterFunc ) Writer { w := & writer { dstW : dstW , } w . zw = newWriter ( & w . xw ) return w }

// NewWriter creates a stackless writer around a writer returned
// from newWriter.
//
// The returned writer writes data to dstW.
//
// Writers that use a lot of stack space may be wrapped into stackless writer,
// thus saving stack space for high number of concurrently running goroutines.

NewWriter creates a stackless writer around a writer returned from newWriter . The returned writer writes data to dstW . Writers that use a lot of stack space may be wrapped into stackless writer thus saving stack space for high number of concurrently running goroutines .


func NewPipeConns() *PipeConns {
	ch1 := make(chan *byteBuffer, 4)
	ch2 := make(chan *byteBuffer, 4)

	pc := &PipeConns{
		stopCh: make(chan struct{}),
	}
	pc.c1.rCh = ch1
	pc.c1.wCh = ch2
	pc.c2.rCh = ch2
	pc.c2.wCh = ch1
	pc.c1.pc = pc
	pc.c2.pc = pc
	return pc
}

func NewPipeConns ( ) * PipeConns { ch1 := make ( chan * byteBuffer , 4 ) ch2 := make ( chan * byteBuffer , 4 ) pc := & PipeConns { stopCh : make ( chan struct { } ) , } pc . c1 . rCh = ch1 pc . c1 . wCh = ch2 pc . c2 . rCh = ch2 pc . c2 . wCh = ch1 pc . c1 . pc = pc pc . c2 . pc = pc return pc }

// NewPipeConns returns new bi-directional connection pipe.

NewPipeConns returns new bi - directional connection pipe .


func (pc *PipeConns) Close() error {
	pc.stopChLock.Lock()
	select {
	case <-pc.stopCh:
	default:
		close(pc.stopCh)
	}
	pc.stopChLock.Unlock()

	return nil
}

func ( pc * PipeConns ) Close ( ) error { pc . stopChLock . Lock ( ) select { case <- pc . stopCh : default : close ( pc . stopCh ) } pc . stopChLock . Unlock ( ) return nil }


func (c *HostClient) LastUseTime() time.Time {
	n := atomic.LoadUint32(&c.lastUseTime)
	return time.Unix(startTimeUnix+int64(n), 0)
}

func ( c * HostClient ) LastUseTime ( ) time . Time { n := atomic . LoadUint32 ( & c . lastUseTime ) return time . Unix ( startTimeUnix + int64 ( n ) , 0 ) }

// LastUseTime returns time the client was last used


func AcquireRequest() *Request {
	v := requestPool.Get()
	if v == nil {
		return &Request{}
	}
	return v.(*Request)
}

func AcquireRequest ( ) * Request { v := requestPool . Get ( ) if v == nil { return & Request { } } return v . ( * Request ) }

// AcquireRequest returns an empty Request instance from request pool.
//
// The returned Request instance may be passed to ReleaseRequest when it is
// no longer needed. This allows Request recycling, reduces GC pressure
// and usually improves performance.

AcquireRequest returns an empty Request instance from request pool . The returned Request instance may be passed to ReleaseRequest when it is no longer needed . This allows Request recycling reduces GC pressure and usually improves performance .


func AcquireResponse() *Response {
	v := responsePool.Get()
	if v == nil {
		return &Response{}
	}
	return v.(*Response)
}

func AcquireResponse ( ) * Response { v := responsePool . Get ( ) if v == nil { return & Response { } } return v . ( * Response ) }

// AcquireResponse returns an empty Response instance from response pool.
//
// The returned Response instance may be passed to ReleaseResponse when it is
// no longer needed. This allows Response recycling, reduces GC pressure
// and usually improves performance.

AcquireResponse returns an empty Response instance from response pool . The returned Response instance may be passed to ReleaseResponse when it is no longer needed . This allows Response recycling reduces GC pressure and usually improves performance .


func (cc *LBClient) DoDeadline(req *Request, resp *Response, deadline time.Time) error {
	return cc.get().DoDeadline(req, resp, deadline)
}

func ( cc * LBClient ) DoDeadline ( req * Request , resp * Response , deadline time . Time ) error { return cc . get ( ) . DoDeadline ( req , resp , deadline ) }

// DoDeadline calls DoDeadline on the least loaded client


func (cc *LBClient) DoTimeout(req *Request, resp *Response, timeout time.Duration) error {
	deadline := time.Now().Add(timeout)
	return cc.get().DoDeadline(req, resp, deadline)
}

func ( cc * LBClient ) DoTimeout ( req * Request , resp * Response , timeout time . Duration ) error { deadline := time . Now ( ) . Add ( timeout ) return cc . get ( ) . DoDeadline ( req , resp , deadline ) }

// DoTimeout calculates deadline and calls DoDeadline on the least loaded client


func (cc *LBClient) Do(req *Request, resp *Response) error {
	timeout := cc.Timeout
	if timeout <= 0 {
		timeout = DefaultLBClientTimeout
	}
	return cc.DoTimeout(req, resp, timeout)
}

func ( cc * LBClient ) Do ( req * Request , resp * Response ) error { timeout := cc . Timeout if timeout <= 0 { timeout = DefaultLBClientTimeout } return cc . DoTimeout ( req , resp , timeout ) }

// Do calls calculates deadline using LBClient.Timeout and calls DoDeadline
// on the least loaded client.

Do calls calculates deadline using LBClient . Timeout and calls DoDeadline on the least loaded client .


func Serve(ln net.Listener, handler RequestHandler) error {
	s := &Server{
		Handler: handler,
	}
	return s.Serve(ln)
}

func Serve ( ln net . Listener , handler RequestHandler ) error { s := & Server { Handler : handler , } return s . Serve ( ln ) }

// Serve serves incoming connections from the given listener
// using the given handler.
//
// Serve blocks until the given listener returns permanent error.

Serve serves incoming connections from the given listener using the given handler . Serve blocks until the given listener returns permanent error .


func ServeTLS(ln net.Listener, certFile, keyFile string, handler RequestHandler) error {
	s := &Server{
		Handler: handler,
	}
	return s.ServeTLS(ln, certFile, keyFile)
}

func ServeTLS ( ln net . Listener , certFile , keyFile string , handler RequestHandler ) error { s := & Server { Handler : handler , } return s . ServeTLS ( ln , certFile , keyFile ) }

// ServeTLS serves HTTPS requests from the given net.Listener
// using the given handler.
//
// certFile and keyFile are paths to TLS certificate and key files.

ServeTLS serves HTTPS requests from the given net . Listener using the given handler . certFile and keyFile are paths to TLS certificate and key files .


func ServeTLSEmbed(ln net.Listener, certData, keyData []byte, handler RequestHandler) error {
	s := &Server{
		Handler: handler,
	}
	return s.ServeTLSEmbed(ln, certData, keyData)
}

func ServeTLSEmbed ( ln net . Listener , certData , keyData [ ] byte , handler RequestHandler ) error { s := & Server { Handler : handler , } return s . ServeTLSEmbed ( ln , certData , keyData ) }

// ServeTLSEmbed serves HTTPS requests from the given net.Listener
// using the given handler.
//
// certData and keyData must contain valid TLS certificate and key data.

ServeTLSEmbed serves HTTPS requests from the given net . Listener using the given handler . certData and keyData must contain valid TLS certificate and key data .


func ListenAndServe(addr string, handler RequestHandler) error {
	s := &Server{
		Handler: handler,
	}
	return s.ListenAndServe(addr)
}

func ListenAndServe ( addr string , handler RequestHandler ) error { s := & Server { Handler : handler , } return s . ListenAndServe ( addr ) }

// ListenAndServe serves HTTP requests from the given TCP addr
// using the given handler.

ListenAndServe serves HTTP requests from the given TCP addr using the given handler .


func ListenAndServeUNIX(addr string, mode os.FileMode, handler RequestHandler) error {
	s := &Server{
		Handler: handler,
	}
	return s.ListenAndServeUNIX(addr, mode)
}

func ListenAndServeUNIX ( addr string , mode os . FileMode , handler RequestHandler ) error { s := & Server { Handler : handler , } return s . ListenAndServeUNIX ( addr , mode ) }

// ListenAndServeUNIX serves HTTP requests from the given UNIX addr
// using the given handler.
//
// The function deletes existing file at addr before starting serving.
//
// The server sets the given file mode for the UNIX addr.

ListenAndServeUNIX serves HTTP requests from the given UNIX addr using the given handler . The function deletes existing file at addr before starting serving . The server sets the given file mode for the UNIX addr .


func ListenAndServeTLS(addr, certFile, keyFile string, handler RequestHandler) error {
	s := &Server{
		Handler: handler,
	}
	return s.ListenAndServeTLS(addr, certFile, keyFile)
}

func ListenAndServeTLS ( addr , certFile , keyFile string , handler RequestHandler ) error { s := & Server { Handler : handler , } return s . ListenAndServeTLS ( addr , certFile , keyFile ) }

// ListenAndServeTLS serves HTTPS requests from the given TCP addr
// using the given handler.
//
// certFile and keyFile are paths to TLS certificate and key files.

ListenAndServeTLS serves HTTPS requests from the given TCP addr using the given handler . certFile and keyFile are paths to TLS certificate and key files .


func ListenAndServeTLSEmbed(addr string, certData, keyData []byte, handler RequestHandler) error {
	s := &Server{
		Handler: handler,
	}
	return s.ListenAndServeTLSEmbed(addr, certData, keyData)
}

func ListenAndServeTLSEmbed ( addr string , certData , keyData [ ] byte , handler RequestHandler ) error { s := & Server { Handler : handler , } return s . ListenAndServeTLSEmbed ( addr , certData , keyData ) }

// ListenAndServeTLSEmbed serves HTTPS requests from the given TCP addr
// using the given handler.
//
// certData and keyData must contain valid TLS certificate and key data.

ListenAndServeTLSEmbed serves HTTPS requests from the given TCP addr using the given handler . certData and keyData must contain valid TLS certificate and key data .


func TimeoutHandler(h RequestHandler, timeout time.Duration, msg string) RequestHandler {
	if timeout <= 0 {
		return h
	}

	return func(ctx *RequestCtx) {
		concurrencyCh := ctx.s.concurrencyCh
		select {
		case concurrencyCh <- struct{}{}:
		default:
			ctx.Error(msg, StatusTooManyRequests)
			return
		}

		ch := ctx.timeoutCh
		if ch == nil {
			ch = make(chan struct{}, 1)
			ctx.timeoutCh = ch
		}
		go func() {
			h(ctx)
			ch <- struct{}{}
			<-concurrencyCh
		}()
		ctx.timeoutTimer = initTimer(ctx.timeoutTimer, timeout)
		select {
		case <-ch:
		case <-ctx.timeoutTimer.C:
			ctx.TimeoutError(msg)
		}
		stopTimer(ctx.timeoutTimer)
	}
}

func TimeoutHandler ( h RequestHandler , timeout time . Duration , msg string ) RequestHandler { if timeout <= 0 { return h } return func ( ctx * RequestCtx ) { concurrencyCh := ctx . s . concurrencyCh select { case concurrencyCh <- struct { } { } : default : ctx . Error ( msg , StatusTooManyRequests ) return } ch := ctx . timeoutCh if ch == nil { ch = make ( chan struct { } , 1 ) ctx . timeoutCh = ch } go func ( ) { h ( ctx ) ch <- struct { } { } <- concurrencyCh } ( ) ctx . timeoutTimer = initTimer ( ctx . timeoutTimer , timeout ) select { case <- ch : case <- ctx . timeoutTimer . C : ctx . TimeoutError ( msg ) } stopTimer ( ctx . timeoutTimer ) } }

// TimeoutHandler creates RequestHandler, which returns StatusRequestTimeout
// error with the given msg to the client if h didn't return during
// the given duration.
//
// The returned handler may return StatusTooManyRequests error with the given
// msg to the client if there are more than Server.Concurrency concurrent
// handlers h are running at the moment.

TimeoutHandler creates RequestHandler which returns StatusRequestTimeout error with the given msg to the client if h didn t return during the given duration . The returned handler may return StatusTooManyRequests error with the given msg to the client if there are more than Server . Concurrency concurrent handlers h are running at the moment .


func (ctx *RequestCtx) TLSConnectionState() *tls.ConnectionState {
	tlsConn, ok := ctx.c.(connTLSer)
	if !ok {
		return nil
	}
	state := tlsConn.ConnectionState()
	return &state
}

func ( ctx * RequestCtx ) TLSConnectionState ( ) * tls . ConnectionState { tlsConn , ok := ctx . c . ( connTLSer ) if ! ok { return nil } state := tlsConn . ConnectionState ( ) return & state }

// TLSConnectionState returns TLS connection state.
//
// The function returns nil if the underlying connection isn't tls.Conn.
//
// The returned state may be used for verifying TLS version, client certificates,
// etc.

TLSConnectionState returns TLS connection state . The function returns nil if the underlying connection isn t tls . Conn . The returned state may be used for verifying TLS version client certificates etc .


func (ctx *RequestCtx) String() string {
	return fmt.Sprintf("#%016X - %s<->%s - %s %s", ctx.ID(), ctx.LocalAddr(), ctx.RemoteAddr(), ctx.Request.Header.Method(), ctx.URI().FullURI())
}

func ( ctx * RequestCtx ) String ( ) string { return fmt . Sprintf ( " " , ctx . ID ( ) , ctx . LocalAddr ( ) , ctx . RemoteAddr ( ) , ctx . Request . Header . Method ( ) , ctx . URI ( ) . FullURI ( ) ) }

// String returns unique string representation of the ctx.
//
// The returned value may be useful for logging.

String returns unique string representation of the ctx . The returned value may be useful for logging .


func (ctx *RequestCtx) SetContentType(contentType string) {
	ctx.Response.Header.SetContentType(contentType)
}

func ( ctx * RequestCtx ) SetContentType ( contentType string ) { ctx . Response . Header . SetContentType ( contentType ) }

// SetContentType sets response Content-Type.

SetContentType sets response Content - Type .


func (ctx *RequestCtx) SetContentTypeBytes(contentType []byte) {
	ctx.Response.Header.SetContentTypeBytes(contentType)
}

func ( ctx * RequestCtx ) SetContentTypeBytes ( contentType [ ] byte ) { ctx . Response . Header . SetContentTypeBytes ( contentType ) }

// SetContentTypeBytes sets response Content-Type.
//
// It is safe modifying contentType buffer after function return.

SetContentTypeBytes sets response Content - Type . It is safe modifying contentType buffer after function return .


func (ctx *RequestCtx) FormFile(key string) (*multipart.FileHeader, error) {
	mf, err := ctx.MultipartForm()
	if err != nil {
		return nil, err
	}
	if mf.File == nil {
		return nil, err
	}
	fhh := mf.File[key]
	if fhh == nil {
		return nil, ErrMissingFile
	}
	return fhh[0], nil
}

func ( ctx * RequestCtx ) FormFile ( key string ) ( * multipart . FileHeader , error ) { mf , err := ctx . MultipartForm ( ) if err != nil { return nil , err } if mf . File == nil { return nil , err } fhh := mf . File [ key ] if fhh == nil { return nil , ErrMissingFile } return fhh [ 0 ] , nil }

// FormFile returns uploaded file associated with the given multipart form key.
//
// The file is automatically deleted after returning from RequestHandler,
// so either move or copy uploaded file into new place if you want retaining it.
//
// Use SaveMultipartFile function for permanently saving uploaded file.
//
// The returned file header is valid until returning from RequestHandler.

FormFile returns uploaded file associated with the given multipart form key . The file is automatically deleted after returning from RequestHandler so either move or copy uploaded file into new place if you want retaining it . Use SaveMultipartFile function for permanently saving uploaded file . The returned file header is valid until returning from RequestHandler .


func SaveMultipartFile(fh *multipart.FileHeader, path string) error {
	f, err := fh.Open()
	if err != nil {
		return err
	}

	if ff, ok := f.(*os.File); ok {
		// Windows can't rename files that are opened.
		if err := f.Close(); err != nil {
			return err
		}

		// If renaming fails we try the normal copying method.
		// Renaming could fail if the files are on different devices.
		if os.Rename(ff.Name(), path) == nil {
			return nil
		}

		// Reopen f for the code below.
		f, err = fh.Open()
		if err != nil {
			return err
		}
	}

	defer f.Close()

	ff, err := os.Create(path)
	if err != nil {
		return err
	}
	defer ff.Close()
	_, err = copyZeroAlloc(ff, f)
	return err
}

// SaveMultipartFile saves multipart file fh under the given filename path.

SaveMultipartFile saves multipart file fh under the given filename path .


func (ctx *RequestCtx) RemoteAddr() net.Addr {
	if ctx.c == nil {
		return zeroTCPAddr
	}
	addr := ctx.c.RemoteAddr()
	if addr == nil {
		return zeroTCPAddr
	}
	return addr
}

func ( ctx * RequestCtx ) RemoteAddr ( ) net . Addr { if ctx . c == nil { return zeroTCPAddr } addr := ctx . c . RemoteAddr ( ) if addr == nil { return zeroTCPAddr } return addr }

// RemoteAddr returns client address for the given request.
//
// Always returns non-nil result.

RemoteAddr returns client address for the given request . Always returns non - nil result .


func (ctx *RequestCtx) Error(msg string, statusCode int) {
	ctx.Response.Reset()
	ctx.SetStatusCode(statusCode)
	ctx.SetContentTypeBytes(defaultContentType)
	ctx.SetBodyString(msg)
}

func ( ctx * RequestCtx ) Error ( msg string , statusCode int ) { ctx . Response . Reset ( ) ctx . SetStatusCode ( statusCode ) ctx . SetContentTypeBytes ( defaultContentType ) ctx . SetBodyString ( msg ) }

// Error sets response status code to the given value and sets response body
// to the given message.

Error sets response status code to the given value and sets response body to the given message .


func (ctx *RequestCtx) Success(contentType string, body []byte) {
	ctx.SetContentType(contentType)
	ctx.SetBody(body)
}

func ( ctx * RequestCtx ) Success ( contentType string , body [ ] byte ) { ctx . SetContentType ( contentType ) ctx . SetBody ( body ) }

// Success sets response Content-Type and body to the given values.

Success sets response Content - Type and body to the given values .


func (ctx *RequestCtx) SuccessString(contentType, body string) {
	ctx.SetContentType(contentType)
	ctx.SetBodyString(body)
}

func ( ctx * RequestCtx ) SuccessString ( contentType , body string ) { ctx . SetContentType ( contentType ) ctx . SetBodyString ( body ) }

// SuccessString sets response Content-Type and body to the given values.

SuccessString sets response Content - Type and body to the given values .


func (ctx *RequestCtx) IfModifiedSince(lastModified time.Time) bool {
	ifModStr := ctx.Request.Header.peek(strIfModifiedSince)
	if len(ifModStr) == 0 {
		return true
	}
	ifMod, err := ParseHTTPDate(ifModStr)
	if err != nil {
		return true
	}
	lastModified = lastModified.Truncate(time.Second)
	return ifMod.Before(lastModified)
}

func ( ctx * RequestCtx ) IfModifiedSince ( lastModified time . Time ) bool { ifModStr := ctx . Request . Header . peek ( strIfModifiedSince ) if len ( ifModStr ) == 0 { return true } ifMod , err := ParseHTTPDate ( ifModStr ) if err != nil { return true } lastModified = lastModified . Truncate ( time . Second ) return ifMod . Before ( lastModified ) }

// IfModifiedSince returns true if lastModified exceeds 'If-Modified-Since'
// value from the request header.
//
// The function returns true also 'If-Modified-Since' request header is missing.

IfModifiedSince returns true if lastModified exceeds If - Modified - Since value from the request header . The function returns true also If - Modified - Since request header is missing .


func (ctx *RequestCtx) NotFound() {
	ctx.Response.Reset()
	ctx.SetStatusCode(StatusNotFound)
	ctx.SetBodyString("404 Page not found")
}

func ( ctx * RequestCtx ) NotFound ( ) { ctx . Response . Reset ( ) ctx . SetStatusCode ( StatusNotFound ) ctx . SetBodyString ( " " ) }

// NotFound resets response and sets '404 Not Found' response status code.

NotFound resets response and sets 404 Not Found response status code .


func (ctx *RequestCtx) Write(p []byte) (int, error) {
	ctx.Response.AppendBody(p)
	return len(p), nil
}

func ( ctx * RequestCtx ) Write ( p [ ] byte ) ( int , error ) { ctx . Response . AppendBody ( p ) return len ( p ) , nil }


func (ctx *RequestCtx) WriteString(s string) (int, error) {
	ctx.Response.AppendBodyString(s)
	return len(s), nil
}

func ( ctx * RequestCtx ) WriteString ( s string ) ( int , error ) { ctx . Response . AppendBodyString ( s ) return len ( s ) , nil }

// WriteString appends s to response body.

WriteString appends s to response body .


func (ctx *RequestCtx) Logger() Logger {
	if ctx.logger.ctx == nil {
		ctx.logger.ctx = ctx
	}
	if ctx.logger.logger == nil {
		ctx.logger.logger = ctx.s.logger()
	}
	return &ctx.logger
}

func ( ctx * RequestCtx ) Logger ( ) Logger { if ctx . logger . ctx == nil { ctx . logger . ctx = ctx } if ctx . logger . logger == nil { ctx . logger . logger = ctx . s . logger ( ) } return & ctx . logger }

// Logger returns logger, which may be used for logging arbitrary
// request-specific messages inside RequestHandler.
//
// Each message logged via returned logger contains request-specific information
// such as request id, request duration, local address, remote address,
// request method and request url.
//
// It is safe re-using returned logger for logging multiple messages
// for the current request.
//
// The returned logger is valid until returning from RequestHandler.

Logger returns logger which may be used for logging arbitrary request - specific messages inside RequestHandler . Each message logged via returned logger contains request - specific information such as request id request duration local address remote address request method and request url . It is safe re - using returned logger for logging multiple messages for the current request . The returned logger is valid until returning from RequestHandler .


func (s *Server) NextProto(key string, nph ServeHandler) {
	if s.nextProtos == nil {
		s.nextProtos = make(map[string]ServeHandler)
	}
	s.configTLS()
	s.tlsConfig.NextProtos = append(s.tlsConfig.NextProtos, key)
	s.nextProtos[key] = nph
}

func ( s * Server ) NextProto ( key string , nph ServeHandler ) { if s . nextProtos == nil { s . nextProtos = make ( map [ string ] ServeHandler ) } s . configTLS ( ) s . tlsConfig . NextProtos = append ( s . tlsConfig . NextProtos , key ) s . nextProtos [ key ] = nph }

// NextProto adds nph to be processed when key is negotiated when TLS
// connection is established.
//
// This function can only be called before the server is started.

NextProto adds nph to be processed when key is negotiated when TLS connection is established . This function can only be called before the server is started .


func (s *Server) ListenAndServe(addr string) error {
	ln, err := net.Listen("tcp4", addr)
	if err != nil {
		return err
	}
	if s.TCPKeepalive {
		if tcpln, ok := ln.(*net.TCPListener); ok {
			return s.Serve(tcpKeepaliveListener{
				TCPListener:     tcpln,
				keepalivePeriod: s.TCPKeepalivePeriod,
			})
		}
	}
	return s.Serve(ln)
}

func ( s * Server ) ListenAndServe ( addr string ) error { ln , err := net . Listen ( " " , addr ) if err != nil { return err } if s . TCPKeepalive { if tcpln , ok := ln . ( * net . TCPListener ) ; ok { return s . Serve ( tcpKeepaliveListener { TCPListener : tcpln , keepalivePeriod : s . TCPKeepalivePeriod , } ) } } return s . Serve ( ln ) }

// ListenAndServe serves HTTP requests from the given TCP4 addr.
//
// Pass custom listener to Serve if you need listening on non-TCP4 media
// such as IPv6.
//
// Accepted connections are configured to enable TCP keep-alives.

ListenAndServe serves HTTP requests from the given TCP4 addr . Pass custom listener to Serve if you need listening on non - TCP4 media such as IPv6 . Accepted connections are configured to enable TCP keep - alives .


func (s *Server) ListenAndServeUNIX(addr string, mode os.FileMode) error {
	if err := os.Remove(addr); err != nil && !os.IsNotExist(err) {
		return fmt.Errorf("unexpected error when trying to remove unix socket file %q: %s", addr, err)
	}
	ln, err := net.Listen("unix", addr)
	if err != nil {
		return err
	}
	if err = os.Chmod(addr, mode); err != nil {
		return fmt.Errorf("cannot chmod %#o for %q: %s", mode, addr, err)
	}
	return s.Serve(ln)
}

func ( s * Server ) ListenAndServeUNIX ( addr string , mode os . FileMode ) error { if err := os . Remove ( addr ) ; err != nil && ! os . IsNotExist ( err ) { return fmt . Errorf ( " " , addr , err ) } ln , err := net . Listen ( " " , addr ) if err != nil { return err } if err = os . Chmod ( addr , mode ) ; err != nil { return fmt . Errorf ( " " , mode , addr , err ) } return s . Serve ( ln ) }

// ListenAndServeUNIX serves HTTP requests from the given UNIX addr.
//
// The function deletes existing file at addr before starting serving.
//
// The server sets the given file mode for the UNIX addr.

ListenAndServeUNIX serves HTTP requests from the given UNIX addr . The function deletes existing file at addr before starting serving . The server sets the given file mode for the UNIX addr .


func (s *Server) ListenAndServeTLS(addr, certFile, keyFile string) error {
	ln, err := net.Listen("tcp4", addr)
	if err != nil {
		return err
	}
	if s.TCPKeepalive {
		if tcpln, ok := ln.(*net.TCPListener); ok {
			return s.ServeTLS(tcpKeepaliveListener{
				TCPListener:     tcpln,
				keepalivePeriod: s.TCPKeepalivePeriod,
			}, certFile, keyFile)
		}
	}
	return s.ServeTLS(ln, certFile, keyFile)
}

func ( s * Server ) ListenAndServeTLS ( addr , certFile , keyFile string ) error { ln , err := net . Listen ( " " , addr ) if err != nil { return err } if s . TCPKeepalive { if tcpln , ok := ln . ( * net . TCPListener ) ; ok { return s . ServeTLS ( tcpKeepaliveListener { TCPListener : tcpln , keepalivePeriod : s . TCPKeepalivePeriod , } , certFile , keyFile ) } } return s . ServeTLS ( ln , certFile , keyFile ) }

// ListenAndServeTLS serves HTTPS requests from the given TCP4 addr.
//
// certFile and keyFile are paths to TLS certificate and key files.
//
// Pass custom listener to Serve if you need listening on non-TCP4 media
// such as IPv6.
//
// If the certFile or keyFile has not been provided to the server structure,
// the function will use the previously added TLS configuration.
//
// Accepted connections are configured to enable TCP keep-alives.

ListenAndServeTLS serves HTTPS requests from the given TCP4 addr . certFile and keyFile are paths to TLS certificate and key files . Pass custom listener to Serve if you need listening on non - TCP4 media such as IPv6 . If the certFile or keyFile has not been provided to the server structure the function will use the previously added TLS configuration . Accepted connections are configured to enable TCP keep - alives .


func (s *Server) ListenAndServeTLSEmbed(addr string, certData, keyData []byte) error {
	ln, err := net.Listen("tcp4", addr)
	if err != nil {
		return err
	}
	if s.TCPKeepalive {
		if tcpln, ok := ln.(*net.TCPListener); ok {
			return s.ServeTLSEmbed(tcpKeepaliveListener{
				TCPListener:     tcpln,
				keepalivePeriod: s.TCPKeepalivePeriod,
			}, certData, keyData)
		}
	}
	return s.ServeTLSEmbed(ln, certData, keyData)
}

func ( s * Server ) ListenAndServeTLSEmbed ( addr string , certData , keyData [ ] byte ) error { ln , err := net . Listen ( " " , addr ) if err != nil { return err } if s . TCPKeepalive { if tcpln , ok := ln . ( * net . TCPListener ) ; ok { return s . ServeTLSEmbed ( tcpKeepaliveListener { TCPListener : tcpln , keepalivePeriod : s . TCPKeepalivePeriod , } , certData , keyData ) } } return s . ServeTLSEmbed ( ln , certData , keyData ) }

// ListenAndServeTLSEmbed serves HTTPS requests from the given TCP4 addr.
//
// certData and keyData must contain valid TLS certificate and key data.
//
// Pass custom listener to Serve if you need listening on arbitrary media
// such as IPv6.
//
// If the certFile or keyFile has not been provided the server structure,
// the function will use previously added TLS configuration.
//
// Accepted connections are configured to enable TCP keep-alives.

ListenAndServeTLSEmbed serves HTTPS requests from the given TCP4 addr . certData and keyData must contain valid TLS certificate and key data . Pass custom listener to Serve if you need listening on arbitrary media such as IPv6 . If the certFile or keyFile has not been provided the server structure the function will use previously added TLS configuration . Accepted connections are configured to enable TCP keep - alives .


func (s *Server) ServeTLS(ln net.Listener, certFile, keyFile string) error {
	err := s.AppendCert(certFile, keyFile)
	if err != nil && err != errNoCertOrKeyProvided {
		return err
	}
	if s.tlsConfig == nil {
		return errNoCertOrKeyProvided
	}
	s.tlsConfig.BuildNameToCertificate()

	return s.Serve(
		tls.NewListener(ln, s.tlsConfig),
	)
}

func ( s * Server ) ServeTLS ( ln net . Listener , certFile , keyFile string ) error { err := s . AppendCert ( certFile , keyFile ) if err != nil && err != errNoCertOrKeyProvided { return err } if s . tlsConfig == nil { return errNoCertOrKeyProvided } s . tlsConfig . BuildNameToCertificate ( ) return s . Serve ( tls . NewListener ( ln , s . tlsConfig ) , ) }

// ServeTLS serves HTTPS requests from the given listener.
//
// certFile and keyFile are paths to TLS certificate and key files.
//
// If the certFile or keyFile has not been provided the server structure,
// the function will use previously added TLS configuration.

ServeTLS serves HTTPS requests from the given listener . certFile and keyFile are paths to TLS certificate and key files . If the certFile or keyFile has not been provided the server structure the function will use previously added TLS configuration .


func (s *Server) ServeTLSEmbed(ln net.Listener, certData, keyData []byte) error {
	err := s.AppendCertEmbed(certData, keyData)
	if err != nil && err != errNoCertOrKeyProvided {
		return err
	}
	if s.tlsConfig == nil {
		return errNoCertOrKeyProvided
	}
	s.tlsConfig.BuildNameToCertificate()

	return s.Serve(
		tls.NewListener(ln, s.tlsConfig),
	)
}

func ( s * Server ) ServeTLSEmbed ( ln net . Listener , certData , keyData [ ] byte ) error { err := s . AppendCertEmbed ( certData , keyData ) if err != nil && err != errNoCertOrKeyProvided { return err } if s . tlsConfig == nil { return errNoCertOrKeyProvided } s . tlsConfig . BuildNameToCertificate ( ) return s . Serve ( tls . NewListener ( ln , s . tlsConfig ) , ) }

// ServeTLSEmbed serves HTTPS requests from the given listener.
//
// certData and keyData must contain valid TLS certificate and key data.
//
// If the certFile or keyFile has not been provided the server structure,
// the function will use previously added TLS configuration.

ServeTLSEmbed serves HTTPS requests from the given listener . certData and keyData must contain valid TLS certificate and key data . If the certFile or keyFile has not been provided the server structure the function will use previously added TLS configuration .


func (s *Server) AppendCertEmbed(certData, keyData []byte) error {
	if len(certData) == 0 && len(keyData) == 0 {
		return errNoCertOrKeyProvided
	}

	cert, err := tls.X509KeyPair(certData, keyData)
	if err != nil {
		return fmt.Errorf("cannot load TLS key pair from the provided certData(%d) and keyData(%d): %s",
			len(certData), len(keyData), err)
	}

	s.configTLS()

	s.tlsConfig.Certificates = append(s.tlsConfig.Certificates, cert)
	return nil
}

func ( s * Server ) AppendCertEmbed ( certData , keyData [ ] byte ) error { if len ( certData ) == 0 && len ( keyData ) == 0 { return errNoCertOrKeyProvided } cert , err := tls . X509KeyPair ( certData , keyData ) if err != nil { return fmt . Errorf ( " " , len ( certData ) , len ( keyData ) , err ) } s . configTLS ( ) s . tlsConfig . Certificates = append ( s . tlsConfig . Certificates , cert ) return nil }

// AppendCertEmbed does the same as AppendCert but using in-memory data.

AppendCertEmbed does the same as AppendCert but using in - memory data .


func (s *Server) Serve(ln net.Listener) error {
	var lastOverflowErrorTime time.Time
	var lastPerIPErrorTime time.Time
	var c net.Conn
	var err error

	s.mu.Lock()
	{
		if s.ln != nil {
			s.mu.Unlock()
			return ErrAlreadyServing
		}

		s.ln = ln
		s.done = make(chan struct{})
	}
	s.mu.Unlock()

	maxWorkersCount := s.getConcurrency()
	s.concurrencyCh = make(chan struct{}, maxWorkersCount)
	wp := &workerPool{
		WorkerFunc:      s.serveConn,
		MaxWorkersCount: maxWorkersCount,
		LogAllErrors:    s.LogAllErrors,
		Logger:          s.logger(),
		connState:       s.setState,
	}
	wp.Start()

	// Count our waiting to accept a connection as an open connection.
	// This way we can't get into any weird state where just after accepting
	// a connection Shutdown is called which reads open as 0 because it isn't
	// incremented yet.
	atomic.AddInt32(&s.open, 1)
	defer atomic.AddInt32(&s.open, -1)

	for {
		if c, err = acceptConn(s, ln, &lastPerIPErrorTime); err != nil {
			wp.Stop()
			if err == io.EOF {
				return nil
			}
			return err
		}
		s.setState(c, StateNew)
		atomic.AddInt32(&s.open, 1)
		if !wp.Serve(c) {
			atomic.AddInt32(&s.open, -1)
			s.writeFastError(c, StatusServiceUnavailable,
				"The connection cannot be served because Server.Concurrency limit exceeded")
			c.Close()
			s.setState(c, StateClosed)
			if time.Since(lastOverflowErrorTime) > time.Minute {
				s.logger().Printf("The incoming connection cannot be served, because %d concurrent connections are served. "+
					"Try increasing Server.Concurrency", maxWorkersCount)
				lastOverflowErrorTime = time.Now()
			}

			// The current server reached concurrency limit,
			// so give other concurrently running servers a chance
			// accepting incoming connections on the same address.
			//
			// There is a hope other servers didn't reach their
			// concurrency limits yet :)
			//
			// See also: https://github.com/valyala/fasthttp/pull/485#discussion_r239994990
			if s.SleepWhenConcurrencyLimitsExceeded > 0 {
				time.Sleep(s.SleepWhenConcurrencyLimitsExceeded)
			}
		}
		c = nil
	}
}

// Serve serves incoming connections from the given listener.
//
// Serve blocks until the given listener returns permanent error.

Serve serves incoming connections from the given listener . Serve blocks until the given listener returns permanent error .


func (s *Server) Shutdown() error {
	s.mu.Lock()
	defer s.mu.Unlock()

	atomic.StoreInt32(&s.stop, 1)
	defer atomic.StoreInt32(&s.stop, 0)

	if s.ln == nil {
		return nil
	}

	if err := s.ln.Close(); err != nil {
		return err
	}

	if s.done != nil {
		close(s.done)
	}

	// Closing the listener will make Serve() call Stop on the worker pool.
	// Setting .stop to 1 will make serveConn() break out of its loop.
	// Now we just have to wait until all workers are done.
	for {
		if open := atomic.LoadInt32(&s.open); open == 0 {
			break
		}
		// This is not an optimal solution but using a sync.WaitGroup
		// here causes data races as it's hard to prevent Add() to be called
		// while Wait() is waiting.
		time.Sleep(time.Millisecond * 100)
	}

	s.ln = nil
	return nil
}

// Shutdown gracefully shuts down the server without interrupting any active connections.
// Shutdown works by first closing all open listeners and then waiting indefinitely for all connections to return to idle and then shut down.
//
// When Shutdown is called, Serve, ListenAndServe, and ListenAndServeTLS immediately return nil.
// Make sure the program doesn't exit and waits instead for Shutdown to return.
//
// Shutdown does not close keepalive connections so its recommended to set ReadTimeout to something else than 0.

Shutdown gracefully shuts down the server without interrupting any active connections . Shutdown works by first closing all open listeners and then waiting indefinitely for all connections to return to idle and then shut down . When Shutdown is called Serve ListenAndServe and ListenAndServeTLS immediately return nil . Make sure the program doesn t exit and waits instead for Shutdown to return . Shutdown does not close keepalive connections so its recommended to set ReadTimeout to something else than 0 .


func WriteGzip(w io.Writer, p []byte) (int, error) {
	return WriteGzipLevel(w, p, CompressDefaultCompression)
}

func WriteGzip ( w io . Writer , p [ ] byte ) ( int , error ) { return WriteGzipLevel ( w , p , CompressDefaultCompression ) }

// WriteGzip writes gzipped p to w and returns the number of compressed
// bytes written to w.

WriteGzip writes gzipped p to w and returns the number of compressed bytes written to w .


func WriteGunzip(w io.Writer, p []byte) (int, error) {
	r := &byteSliceReader{p}
	zr, err := acquireGzipReader(r)
	if err != nil {
		return 0, err
	}
	n, err := copyZeroAlloc(w, zr)
	releaseGzipReader(zr)
	nn := int(n)
	if int64(nn) != n {
		return 0, fmt.Errorf("too much data gunzipped: %d", n)
	}
	return nn, err
}

func WriteGunzip ( w io . Writer , p [ ] byte ) ( int , error ) { r := & byteSliceReader { p } zr , err := acquireGzipReader ( r ) if err != nil { return 0 , err } n , err := copyZeroAlloc ( w , zr ) releaseGzipReader ( zr ) nn := int ( n ) if int64 ( nn ) != n { return 0 , fmt . Errorf ( " " , n ) } return nn , err }

// WriteGunzip writes ungzipped p to w and returns the number of uncompressed
// bytes written to w.

WriteGunzip writes ungzipped p to w and returns the number of uncompressed bytes written to w .


func AppendGunzipBytes(dst, src []byte) ([]byte, error) {
	w := &byteSliceWriter{dst}
	_, err := WriteGunzip(w, src)
	return w.b, err
}

func AppendGunzipBytes ( dst , src [ ] byte ) ( [ ] byte , error ) { w := & byteSliceWriter { dst } _ , err := WriteGunzip ( w , src ) return w . b , err }

// AppendGunzipBytes appends gunzipped src to dst and returns the resulting dst.

AppendGunzipBytes appends gunzipped src to dst and returns the resulting dst .


func WriteDeflate(w io.Writer, p []byte) (int, error) {
	return WriteDeflateLevel(w, p, CompressDefaultCompression)
}

func WriteDeflate ( w io . Writer , p [ ] byte ) ( int , error ) { return WriteDeflateLevel ( w , p , CompressDefaultCompression ) }

// WriteDeflate writes deflated p to w and returns the number of compressed
// bytes written to w.

WriteDeflate writes deflated p to w and returns the number of compressed bytes written to w .


func WriteInflate(w io.Writer, p []byte) (int, error) {
	r := &byteSliceReader{p}
	zr, err := acquireFlateReader(r)
	if err != nil {
		return 0, err
	}
	n, err := copyZeroAlloc(w, zr)
	releaseFlateReader(zr)
	nn := int(n)
	if int64(nn) != n {
		return 0, fmt.Errorf("too much data inflated: %d", n)
	}
	return nn, err
}

func WriteInflate ( w io . Writer , p [ ] byte ) ( int , error ) { r := & byteSliceReader { p } zr , err := acquireFlateReader ( r ) if err != nil { return 0 , err } n , err := copyZeroAlloc ( w , zr ) releaseFlateReader ( zr ) nn := int ( n ) if int64 ( nn ) != n { return 0 , fmt . Errorf ( " " , n ) } return nn , err }

// WriteInflate writes inflated p to w and returns the number of uncompressed
// bytes written to w.

WriteInflate writes inflated p to w and returns the number of uncompressed bytes written to w .


func AppendInflateBytes(dst, src []byte) ([]byte, error) {
	w := &byteSliceWriter{dst}
	_, err := WriteInflate(w, src)
	return w.b, err
}

func AppendInflateBytes ( dst , src [ ] byte ) ( [ ] byte , error ) { w := & byteSliceWriter { dst } _ , err := WriteInflate ( w , src ) return w . b , err }

// AppendInflateBytes appends inflated src to dst and returns the resulting dst.

AppendInflateBytes appends inflated src to dst and returns the resulting dst .


func (req *Request) SetRequestURI(requestURI string) {
	req.Header.SetRequestURI(requestURI)
	req.parsedURI = false
}

func ( req * Request ) SetRequestURI ( requestURI string ) { req . Header . SetRequestURI ( requestURI ) req . parsedURI = false }


func (req *Request) SetRequestURIBytes(requestURI []byte) {
	req.Header.SetRequestURIBytes(requestURI)
	req.parsedURI = false
}

func ( req * Request ) SetRequestURIBytes ( requestURI [ ] byte ) { req . Header . SetRequestURIBytes ( requestURI ) req . parsedURI = false }


func (req *Request) RequestURI() []byte {
	if req.parsedURI {
		requestURI := req.uri.RequestURI()
		req.SetRequestURIBytes(requestURI)
	}
	return req.Header.RequestURI()
}

func ( req * Request ) RequestURI ( ) [ ] byte { if req . parsedURI { requestURI := req . uri . RequestURI ( ) req . SetRequestURIBytes ( requestURI ) } return req . Header . RequestURI ( ) }


func (resp *Response) SendFile(path string) error {
	f, err := os.Open(path)
	if err != nil {
		return err
	}
	fileInfo, err := f.Stat()
	if err != nil {
		f.Close()
		return err
	}
	size64 := fileInfo.Size()
	size := int(size64)
	if int64(size) != size64 {
		size = -1
	}

	resp.Header.SetLastModified(fileInfo.ModTime())
	resp.SetBodyStream(f, size)
	return nil
}

func ( resp * Response ) SendFile ( path string ) error { f , err := os . Open ( path ) if err != nil { return err } fileInfo , err := f . Stat ( ) if err != nil { f . Close ( ) return err } size64 := fileInfo . Size ( ) size := int ( size64 ) if int64 ( size ) != size64 { size = - 1 } resp . Header . SetLastModified ( fileInfo . ModTime ( ) ) resp . SetBodyStream ( f , size ) return nil }

// SendFile registers file on the given path to be used as response body
// when Write is called.
//
// Note that SendFile doesn't set Content-Type, so set it yourself
// with Header.SetContentType.

SendFile registers file on the given path to be used as response body when Write is called . Note that SendFile doesn t set Content - Type so set it yourself with Header . SetContentType .


func (resp *Response) BodyWriter() io.Writer {
	resp.w.r = resp
	return &resp.w
}

func ( resp * Response ) BodyWriter ( ) io . Writer { resp . w . r = resp return & resp . w }

// BodyWriter returns writer for populating response body.
//
// If used inside RequestHandler, the returned writer must not be used
// after returning from RequestHandler. Use RequestCtx.Write
// or SetBodyStreamWriter in this case.

BodyWriter returns writer for populating response body . If used inside RequestHandler the returned writer must not be used after returning from RequestHandler . Use RequestCtx . Write or SetBodyStreamWriter in this case .


func (req *Request) BodyWriter() io.Writer {
	req.w.r = req
	return &req.w
}

func ( req * Request ) BodyWriter ( ) io . Writer { req . w . r = req return & req . w }

// BodyWriter returns writer for populating request body.

BodyWriter returns writer for populating request body .


func (resp *Response) Body() []byte {
	if resp.bodyStream != nil {
		bodyBuf := resp.bodyBuffer()
		bodyBuf.Reset()
		_, err := copyZeroAlloc(bodyBuf, resp.bodyStream)
		resp.closeBodyStream()
		if err != nil {
			bodyBuf.SetString(err.Error())
		}
	}
	return resp.bodyBytes()
}

func ( resp * Response ) Body ( ) [ ] byte { if resp . bodyStream != nil { bodyBuf := resp . bodyBuffer ( ) bodyBuf . Reset ( ) _ , err := copyZeroAlloc ( bodyBuf , resp . bodyStream ) resp . closeBodyStream ( ) if err != nil { bodyBuf . SetString ( err . Error ( ) ) } } return resp . bodyBytes ( ) }

// Body returns response body.
//
// The returned body is valid until the response modification.

Body returns response body . The returned body is valid until the response modification .


func (req *Request) BodyWriteTo(w io.Writer) error {
	if req.bodyStream != nil {
		_, err := copyZeroAlloc(w, req.bodyStream)
		req.closeBodyStream()
		return err
	}
	if req.onlyMultipartForm() {
		return WriteMultipartForm(w, req.multipartForm, req.multipartFormBoundary)
	}
	_, err := w.Write(req.bodyBytes())
	return err
}

func ( req * Request ) BodyWriteTo ( w io . Writer ) error { if req . bodyStream != nil { _ , err := copyZeroAlloc ( w , req . bodyStream ) req . closeBodyStream ( ) return err } if req . onlyMultipartForm ( ) { return WriteMultipartForm ( w , req . multipartForm , req . multipartFormBoundary ) } _ , err := w . Write ( req . bodyBytes ( ) ) return err }

// BodyWriteTo writes request body to w.


func (resp *Response) BodyWriteTo(w io.Writer) error {
	if resp.bodyStream != nil {
		_, err := copyZeroAlloc(w, resp.bodyStream)
		resp.closeBodyStream()
		return err
	}
	_, err := w.Write(resp.bodyBytes())
	return err
}

func ( resp * Response ) BodyWriteTo ( w io . Writer ) error { if resp . bodyStream != nil { _ , err := copyZeroAlloc ( w , resp . bodyStream ) resp . closeBodyStream ( ) return err } _ , err := w . Write ( resp . bodyBytes ( ) ) return err }

// BodyWriteTo writes response body to w.


func (resp *Response) AppendBodyString(s string) {
	resp.closeBodyStream()
	resp.bodyBuffer().WriteString(s)
}

func ( resp * Response ) AppendBodyString ( s string ) { resp . closeBodyStream ( ) resp . bodyBuffer ( ) . WriteString ( s ) }

// AppendBodyString appends s to response body.

AppendBodyString appends s to response body .


func (resp *Response) SetBodyString(body string) {
	resp.closeBodyStream()
	bodyBuf := resp.bodyBuffer()
	bodyBuf.Reset()
	bodyBuf.WriteString(body)
}

func ( resp * Response ) SetBodyString ( body string ) { resp . closeBodyStream ( ) bodyBuf := resp . bodyBuffer ( ) bodyBuf . Reset ( ) bodyBuf . WriteString ( body ) }


func (resp *Response) ResetBody() {
	resp.bodyRaw = nil
	resp.closeBodyStream()
	if resp.body != nil {
		if resp.keepBodyBuffer {
			resp.body.Reset()
		} else {
			responseBodyPool.Put(resp.body)
			resp.body = nil
		}
	}
}

func ( resp * Response ) ResetBody ( ) { resp . bodyRaw = nil resp . closeBodyStream ( ) if resp . body != nil { if resp . keepBodyBuffer { resp . body . Reset ( ) } else { responseBodyPool . Put ( resp . body ) resp . body = nil } } }


func (resp *Response) SetBodyRaw(body []byte) {
	resp.ResetBody()
	resp.bodyRaw = body
}

func ( resp * Response ) SetBodyRaw ( body [ ] byte ) { resp . ResetBody ( ) resp . bodyRaw = body }

// SetBodyRaw sets response body, but without copying it.
//
// From this point onward the body argument must not be changed.

SetBodyRaw sets response body but without copying it . From this point onward the body argument must not be changed .


func (resp *Response) ReleaseBody(size int) {
	resp.bodyRaw = nil
	if cap(resp.body.B) > size {
		resp.closeBodyStream()
		resp.body = nil
	}
}

func ( resp * Response ) ReleaseBody ( size int ) { resp . bodyRaw = nil if cap ( resp . body . B ) > size { resp . closeBodyStream ( ) resp . body = nil } }

// ReleaseBody retires the response body if it is greater than "size" bytes.
//
// This permits GC to reclaim the large buffer.  If used, must be before
// ReleaseResponse.
//
// Use this method only if you really understand how it works.
// The majority of workloads don't need this method.

ReleaseBody retires the response body if it is greater than size bytes . This permits GC to reclaim the large buffer . If used must be before ReleaseResponse . Use this method only if you really understand how it works . The majority of workloads don t need this method .


func (req *Request) ReleaseBody(size int) {
	if cap(req.body.B) > size {
		req.closeBodyStream()
		req.body = nil
	}
}

func ( req * Request ) ReleaseBody ( size int ) { if cap ( req . body . B ) > size { req . closeBodyStream ( ) req . body = nil } }

// ReleaseBody retires the request body if it is greater than "size" bytes.
//
// This permits GC to reclaim the large buffer.  If used, must be before
// ReleaseRequest.
//
// Use this method only if you really understand how it works.
// The majority of workloads don't need this method.

ReleaseBody retires the request body if it is greater than size bytes . This permits GC to reclaim the large buffer . If used must be before ReleaseRequest . Use this method only if you really understand how it works . The majority of workloads don t need this method .


func (resp *Response) SwapBody(body []byte) []byte {
	bb := resp.bodyBuffer()

	if resp.bodyStream != nil {
		bb.Reset()
		_, err := copyZeroAlloc(bb, resp.bodyStream)
		resp.closeBodyStream()
		if err != nil {
			bb.Reset()
			bb.SetString(err.Error())
		}
	}

	resp.bodyRaw = nil

	oldBody := bb.B
	bb.B = body
	return oldBody
}

func ( resp * Response ) SwapBody ( body [ ] byte ) [ ] byte { bb := resp . bodyBuffer ( ) if resp . bodyStream != nil { bb . Reset ( ) _ , err := copyZeroAlloc ( bb , resp . bodyStream ) resp . closeBodyStream ( ) if err != nil { bb . Reset ( ) bb . SetString ( err . Error ( ) ) } } resp . bodyRaw = nil oldBody := bb . B bb . B = body return oldBody }

// SwapBody swaps response body with the given body and returns
// the previous response body.
//
// It is forbidden to use the body passed to SwapBody after
// the function returns.

SwapBody swaps response body with the given body and returns the previous response body . It is forbidden to use the body passed to SwapBody after the function returns .


func (req *Request) SwapBody(body []byte) []byte {
	bb := req.bodyBuffer()

	if req.bodyStream != nil {
		bb.Reset()
		_, err := copyZeroAlloc(bb, req.bodyStream)
		req.closeBodyStream()
		if err != nil {
			bb.Reset()
			bb.SetString(err.Error())
		}
	}

	oldBody := bb.B
	bb.B = body
	return oldBody
}

func ( req * Request ) SwapBody ( body [ ] byte ) [ ] byte { bb := req . bodyBuffer ( ) if req . bodyStream != nil { bb . Reset ( ) _ , err := copyZeroAlloc ( bb , req . bodyStream ) req . closeBodyStream ( ) if err != nil { bb . Reset ( ) bb . SetString ( err . Error ( ) ) } } oldBody := bb . B bb . B = body return oldBody }

// SwapBody swaps request body with the given body and returns
// the previous request body.
//
// It is forbidden to use the body passed to SwapBody after
// the function returns.

SwapBody swaps request body with the given body and returns the previous request body . It is forbidden to use the body passed to SwapBody after the function returns .


func (req *Request) Body() []byte {
	if req.bodyStream != nil {
		bodyBuf := req.bodyBuffer()
		bodyBuf.Reset()
		_, err := copyZeroAlloc(bodyBuf, req.bodyStream)
		req.closeBodyStream()
		if err != nil {
			bodyBuf.SetString(err.Error())
		}
	} else if req.onlyMultipartForm() {
		body, err := marshalMultipartForm(req.multipartForm, req.multipartFormBoundary)
		if err != nil {
			return []byte(err.Error())
		}
		return body
	}
	return req.bodyBytes()
}

func ( req * Request ) Body ( ) [ ] byte { if req . bodyStream != nil { bodyBuf := req . bodyBuffer ( ) bodyBuf . Reset ( ) _ , err := copyZeroAlloc ( bodyBuf , req . bodyStream ) req . closeBodyStream ( ) if err != nil { bodyBuf . SetString ( err . Error ( ) ) } } else if req . onlyMultipartForm ( ) { body , err := marshalMultipartForm ( req . multipartForm , req . multipartFormBoundary ) if err != nil { return [ ] byte ( err . Error ( ) ) } return body } return req . bodyBytes ( ) }

// Body returns request body.
//
// The returned body is valid until the request modification.

Body returns request body . The returned body is valid until the request modification .


func (req *Request) AppendBodyString(s string) {
	req.RemoveMultipartFormFiles()
	req.closeBodyStream()
	req.bodyBuffer().WriteString(s)
}

func ( req * Request ) AppendBodyString ( s string ) { req . RemoveMultipartFormFiles ( ) req . closeBodyStream ( ) req . bodyBuffer ( ) . WriteString ( s ) }

// AppendBodyString appends s to request body.

AppendBodyString appends s to request body .


func (req *Request) SetBodyString(body string) {
	req.RemoveMultipartFormFiles()
	req.closeBodyStream()
	req.bodyBuffer().SetString(body)
}

func ( req * Request ) SetBodyString ( body string ) { req . RemoveMultipartFormFiles ( ) req . closeBodyStream ( ) req . bodyBuffer ( ) . SetString ( body ) }


func (req *Request) ResetBody() {
	req.RemoveMultipartFormFiles()
	req.closeBodyStream()
	if req.body != nil {
		if req.keepBodyBuffer {
			req.body.Reset()
		} else {
			requestBodyPool.Put(req.body)
			req.body = nil
		}
	}
}

func ( req * Request ) ResetBody ( ) { req . RemoveMultipartFormFiles ( ) req . closeBodyStream ( ) if req . body != nil { if req . keepBodyBuffer { req . body . Reset ( ) } else { requestBodyPool . Put ( req . body ) req . body = nil } } }


func (req *Request) CopyTo(dst *Request) {
	req.copyToSkipBody(dst)
	if req.body != nil {
		dst.bodyBuffer().Set(req.body.B)
	} else if dst.body != nil {
		dst.body.Reset()
	}
}

func ( req * Request ) CopyTo ( dst * Request ) { req . copyToSkipBody ( dst ) if req . body != nil { dst . bodyBuffer ( ) . Set ( req . body . B ) } else if dst . body != nil { dst . body . Reset ( ) } }

// CopyTo copies req contents to dst except of body stream.

CopyTo copies req contents to dst except of body stream .


func (resp *Response) CopyTo(dst *Response) {
	resp.copyToSkipBody(dst)
	if resp.bodyRaw != nil {
		dst.bodyRaw = resp.bodyRaw
		if dst.body != nil {
			dst.body.Reset()
		}
	} else if resp.body != nil {
		dst.bodyBuffer().Set(resp.body.B)
	} else if dst.body != nil {
		dst.body.Reset()
	}
}

func ( resp * Response ) CopyTo ( dst * Response ) { resp . copyToSkipBody ( dst ) if resp . bodyRaw != nil { dst . bodyRaw = resp . bodyRaw if dst . body != nil { dst . body . Reset ( ) } } else if resp . body != nil { dst . bodyBuffer ( ) . Set ( resp . body . B ) } else if dst . body != nil { dst . body . Reset ( ) } }

// CopyTo copies resp contents to dst except of body stream.

CopyTo copies resp contents to dst except of body stream .


func WriteMultipartForm(w io.Writer, f *multipart.Form, boundary string) error {
	// Do not care about memory allocations here, since multipart
	// form processing is slow.
	if len(boundary) == 0 {
		panic("BUG: form boundary cannot be empty")
	}

	mw := multipart.NewWriter(w)
	if err := mw.SetBoundary(boundary); err != nil {
		return fmt.Errorf("cannot use form boundary %q: %s", boundary, err)
	}

	// marshal values
	for k, vv := range f.Value {
		for _, v := range vv {
			if err := mw.WriteField(k, v); err != nil {
				return fmt.Errorf("cannot write form field %q value %q: %s", k, v, err)
			}
		}
	}

	// marshal files
	for k, fvv := range f.File {
		for _, fv := range fvv {
			vw, err := mw.CreatePart(fv.Header)
			if err != nil {
				return fmt.Errorf("cannot create form file %q (%q): %s", k, fv.Filename, err)
			}
			fh, err := fv.Open()
			if err != nil {
				return fmt.Errorf("cannot open form file %q (%q): %s", k, fv.Filename, err)
			}
			if _, err = copyZeroAlloc(vw, fh); err != nil {
				return fmt.Errorf("error when copying form file %q (%q): %s", k, fv.Filename, err)
			}
			if err = fh.Close(); err != nil {
				return fmt.Errorf("cannot close form file %q (%q): %s", k, fv.Filename, err)
			}
		}
	}

	if err := mw.Close(); err != nil {
		return fmt.Errorf("error when closing multipart form writer: %s", err)
	}

	return nil
}

// WriteMultipartForm writes the given multipart form f with the given
// boundary to w.

WriteMultipartForm writes the given multipart form f with the given boundary to w .


func (resp *Response) Reset() {
	resp.Header.Reset()
	resp.resetSkipHeader()
	resp.SkipBody = false
	resp.raddr = nil
	resp.laddr = nil
}

func ( resp * Response ) Reset ( ) { resp . Header . Reset ( ) resp . resetSkipHeader ( ) resp . SkipBody = false resp . raddr = nil resp . laddr = nil }


func (resp *Response) ReadLimitBody(r *bufio.Reader, maxBodySize int) error {
	resp.resetSkipHeader()
	err := resp.Header.Read(r)
	if err != nil {
		return err
	}
	if resp.Header.StatusCode() == StatusContinue {
		// Read the next response according to http://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html .
		if err = resp.Header.Read(r); err != nil {
			return err
		}
	}

	if !resp.mustSkipBody() {
		bodyBuf := resp.bodyBuffer()
		bodyBuf.Reset()
		bodyBuf.B, err = readBody(r, resp.Header.ContentLength(), maxBodySize, bodyBuf.B)
		if err != nil {
			return err
		}
		resp.Header.SetContentLength(len(bodyBuf.B))
	}
	return nil
}

// ReadLimitBody reads response from the given r, limiting the body size.
//
// If maxBodySize > 0 and the body size exceeds maxBodySize,
// then ErrBodyTooLarge is returned.
//
// io.EOF is returned if r is closed before reading the first header byte.

ReadLimitBody reads response from the given r limiting the body size . If maxBodySize > 0 and the body size exceeds maxBodySize then ErrBodyTooLarge is returned . io . EOF is returned if r is closed before reading the first header byte .


func (req *Request) WriteTo(w io.Writer) (int64, error) {
	return writeBufio(req, w)
}

func ( req * Request ) WriteTo ( w io . Writer ) ( int64 , error ) { return writeBufio ( req , w ) }

// WriteTo writes request to w. It implements io.WriterTo.

WriteTo writes request to w . It implements io . WriterTo .


func (resp *Response) WriteTo(w io.Writer) (int64, error) {
	return writeBufio(resp, w)
}

func ( resp * Response ) WriteTo ( w io . Writer ) ( int64 , error ) { return writeBufio ( resp , w ) }

// WriteTo writes response to w. It implements io.WriterTo.

WriteTo writes response to w . It implements io . WriterTo .