-
Notifications
You must be signed in to change notification settings - Fork 0
/
template.go
77 lines (66 loc) · 1.53 KB
/
template.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package template
import (
"io"
"net/http"
"strings"
"text/template"
"github.com/pipeproxy/pipe/internal/pool"
)
type Template struct {
template *template.Template
}
func (t *Template) init(text string) error {
temp := template.New("_")
temp, err := temp.Parse(text)
if err != nil {
return err
}
t.template = temp
return nil
}
func (t *Template) Format(w io.Writer, r *http.Request) error {
err := t.template.Execute(w, &RequestVal{r})
if err != nil {
return err
}
return nil
}
func (t *Template) FormatString(r *http.Request) string {
buf := pool.GetBuffer()
defer pool.PutBuffer(buf)
err := t.Format(buf, r)
if err != nil {
return ""
}
return buf.String()
}
// splitHostPort separates host and port. If the port is not valid, it returns
// the entire input as host, and it doesn't check the validity of the host.
// Unlike net.SplitHostPort, but per RFC 3986, it requires ports to be numeric.
func splitHostPort(hostport string) (host, port string) {
host = hostport
colon := strings.LastIndexByte(host, ':')
if colon != -1 && validOptionalPort(host[colon:]) {
host, port = host[:colon], host[colon+1:]
}
if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") {
host = host[1 : len(host)-1]
}
return
}
// validOptionalPort reports whether port is either an empty string
// or matches /^:\d*$/
func validOptionalPort(port string) bool {
if port == "" {
return true
}
if port[0] != ':' {
return false
}
for _, b := range port[1:] {
if b < '0' || b > '9' {
return false
}
}
return true
}