本站源代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

327 lines
6.8KB

  1. // Copyright 2013 The Go Authors. All rights reserved.
  2. //
  3. // Use of this source code is governed by a BSD-style
  4. // license that can be found in the LICENSE file or at
  5. // https://developers.google.com/open-source/licenses/bsd.
  6. // this file was taken from the github.com/golang/gddo repository
  7. // Package header provides functions for parsing HTTP headers.
  8. package header
  9. import (
  10. "net/http"
  11. "strings"
  12. "time"
  13. )
  14. // Octet types from RFC 2616.
  15. var octetTypes [256]octetType
  16. type octetType byte
  17. const (
  18. isToken octetType = 1 << iota
  19. isSpace
  20. )
  21. func init() {
  22. // OCTET = <any 8-bit sequence of data>
  23. // CHAR = <any US-ASCII character (octets 0 - 127)>
  24. // CTL = <any US-ASCII control character (octets 0 - 31) and DEL (127)>
  25. // CR = <US-ASCII CR, carriage return (13)>
  26. // LF = <US-ASCII LF, linefeed (10)>
  27. // SP = <US-ASCII SP, space (32)>
  28. // HT = <US-ASCII HT, horizontal-tab (9)>
  29. // <"> = <US-ASCII double-quote mark (34)>
  30. // CRLF = CR LF
  31. // LWS = [CRLF] 1*( SP | HT )
  32. // TEXT = <any OCTET except CTLs, but including LWS>
  33. // separators = "(" | ")" | "<" | ">" | "@" | "," | ";" | ":" | "\" | <">
  34. // | "/" | "[" | "]" | "?" | "=" | "{" | "}" | SP | HT
  35. // token = 1*<any CHAR except CTLs or separators>
  36. // qdtext = <any TEXT except <">>
  37. for c := 0; c < 256; c++ {
  38. var t octetType
  39. isCtl := c <= 31 || c == 127
  40. isChar := 0 <= c && c <= 127
  41. isSeparator := strings.ContainsRune(" \t\"(),/:;<=>?@[]\\{}", rune(c))
  42. if strings.ContainsRune(" \t\r\n", rune(c)) {
  43. t |= isSpace
  44. }
  45. if isChar && !isCtl && !isSeparator {
  46. t |= isToken
  47. }
  48. octetTypes[c] = t
  49. }
  50. }
  51. // Copy returns a shallow copy of the header.
  52. func Copy(header http.Header) http.Header {
  53. h := make(http.Header)
  54. for k, vs := range header {
  55. h[k] = vs
  56. }
  57. return h
  58. }
  59. var timeLayouts = []string{"Mon, 02 Jan 2006 15:04:05 GMT", time.RFC850, time.ANSIC}
  60. // ParseTime parses the header as time. The zero value is returned if the
  61. // header is not present or there is an error parsing the
  62. // header.
  63. func ParseTime(header http.Header, key string) time.Time {
  64. if s := header.Get(key); s != "" {
  65. for _, layout := range timeLayouts {
  66. if t, err := time.Parse(layout, s); err == nil {
  67. return t.UTC()
  68. }
  69. }
  70. }
  71. return time.Time{}
  72. }
  73. // ParseList parses a comma separated list of values. Commas are ignored in
  74. // quoted strings. Quoted values are not unescaped or unquoted. Whitespace is
  75. // trimmed.
  76. func ParseList(header http.Header, key string) []string {
  77. var result []string
  78. for _, s := range header[http.CanonicalHeaderKey(key)] {
  79. begin := 0
  80. end := 0
  81. escape := false
  82. quote := false
  83. for i := 0; i < len(s); i++ {
  84. b := s[i]
  85. switch {
  86. case escape:
  87. escape = false
  88. end = i + 1
  89. case quote:
  90. switch b {
  91. case '\\':
  92. escape = true
  93. case '"':
  94. quote = false
  95. }
  96. end = i + 1
  97. case b == '"':
  98. quote = true
  99. end = i + 1
  100. case octetTypes[b]&isSpace != 0:
  101. if begin == end {
  102. begin = i + 1
  103. end = begin
  104. }
  105. case b == ',':
  106. if begin < end {
  107. result = append(result, s[begin:end])
  108. }
  109. begin = i + 1
  110. end = begin
  111. default:
  112. end = i + 1
  113. }
  114. }
  115. if begin < end {
  116. result = append(result, s[begin:end])
  117. }
  118. }
  119. return result
  120. }
  121. // ParseValueAndParams parses a comma separated list of values with optional
  122. // semicolon separated name-value pairs. Content-Type and Content-Disposition
  123. // headers are in this format.
  124. func ParseValueAndParams(header http.Header, key string) (string, map[string]string) {
  125. return parseValueAndParams(header.Get(key))
  126. }
  127. func parseValueAndParams(s string) (value string, params map[string]string) {
  128. params = make(map[string]string)
  129. value, s = expectTokenSlash(s)
  130. if value == "" {
  131. return
  132. }
  133. value = strings.ToLower(value)
  134. s = skipSpace(s)
  135. for strings.HasPrefix(s, ";") {
  136. var pkey string
  137. pkey, s = expectToken(skipSpace(s[1:]))
  138. if pkey == "" {
  139. return
  140. }
  141. if !strings.HasPrefix(s, "=") {
  142. return
  143. }
  144. var pvalue string
  145. pvalue, s = expectTokenOrQuoted(s[1:])
  146. if pvalue == "" {
  147. return
  148. }
  149. pkey = strings.ToLower(pkey)
  150. params[pkey] = pvalue
  151. s = skipSpace(s)
  152. }
  153. return
  154. }
  155. // AcceptSpec ...
  156. type AcceptSpec struct {
  157. Value string
  158. Q float64
  159. }
  160. // ParseAccept2 ...
  161. func ParseAccept2(header http.Header, key string) (specs []AcceptSpec) {
  162. for _, en := range ParseList(header, key) {
  163. v, p := parseValueAndParams(en)
  164. var spec AcceptSpec
  165. spec.Value = v
  166. spec.Q = 1.0
  167. if p != nil {
  168. if q, ok := p["q"]; ok {
  169. spec.Q, _ = expectQuality(q)
  170. }
  171. }
  172. if spec.Q < 0.0 {
  173. continue
  174. }
  175. specs = append(specs, spec)
  176. }
  177. return
  178. }
  179. // ParseAccept parses Accept* headers.
  180. func ParseAccept(header http.Header, key string) (specs []AcceptSpec) {
  181. loop:
  182. for _, s := range header[key] {
  183. for {
  184. var spec AcceptSpec
  185. spec.Value, s = expectTokenSlash(s)
  186. if spec.Value == "" {
  187. continue loop
  188. }
  189. spec.Q = 1.0
  190. s = skipSpace(s)
  191. if strings.HasPrefix(s, ";") {
  192. s = skipSpace(s[1:])
  193. for !strings.HasPrefix(s, "q=") && s != "" && !strings.HasPrefix(s, ",") {
  194. s = skipSpace(s[1:])
  195. }
  196. if strings.HasPrefix(s, "q=") {
  197. spec.Q, s = expectQuality(s[2:])
  198. if spec.Q < 0.0 {
  199. continue loop
  200. }
  201. }
  202. }
  203. specs = append(specs, spec)
  204. s = skipSpace(s)
  205. if !strings.HasPrefix(s, ",") {
  206. continue loop
  207. }
  208. s = skipSpace(s[1:])
  209. }
  210. }
  211. return
  212. }
  213. func skipSpace(s string) (rest string) {
  214. i := 0
  215. for ; i < len(s); i++ {
  216. if octetTypes[s[i]]&isSpace == 0 {
  217. break
  218. }
  219. }
  220. return s[i:]
  221. }
  222. func expectToken(s string) (token, rest string) {
  223. i := 0
  224. for ; i < len(s); i++ {
  225. if octetTypes[s[i]]&isToken == 0 {
  226. break
  227. }
  228. }
  229. return s[:i], s[i:]
  230. }
  231. func expectTokenSlash(s string) (token, rest string) {
  232. i := 0
  233. for ; i < len(s); i++ {
  234. b := s[i]
  235. if (octetTypes[b]&isToken == 0) && b != '/' {
  236. break
  237. }
  238. }
  239. return s[:i], s[i:]
  240. }
  241. func expectQuality(s string) (q float64, rest string) {
  242. switch {
  243. case len(s) == 0:
  244. return -1, ""
  245. case s[0] == '0':
  246. q = 0
  247. case s[0] == '1':
  248. q = 1
  249. default:
  250. return -1, ""
  251. }
  252. s = s[1:]
  253. if !strings.HasPrefix(s, ".") {
  254. return q, s
  255. }
  256. s = s[1:]
  257. i := 0
  258. n := 0
  259. d := 1
  260. for ; i < len(s); i++ {
  261. b := s[i]
  262. if b < '0' || b > '9' {
  263. break
  264. }
  265. n = n*10 + int(b) - '0'
  266. d *= 10
  267. }
  268. return q + float64(n)/float64(d), s[i:]
  269. }
  270. func expectTokenOrQuoted(s string) (value string, rest string) {
  271. if !strings.HasPrefix(s, "\"") {
  272. return expectToken(s)
  273. }
  274. s = s[1:]
  275. for i := 0; i < len(s); i++ {
  276. switch s[i] {
  277. case '"':
  278. return s[:i], s[i+1:]
  279. case '\\':
  280. p := make([]byte, len(s)-1)
  281. j := copy(p, s[:i])
  282. escape := true
  283. for i = i + 1; i < len(s); i++ {
  284. b := s[i]
  285. switch {
  286. case escape:
  287. escape = false
  288. p[j] = b
  289. j++
  290. case b == '\\':
  291. escape = true
  292. case b == '"':
  293. return string(p[:j]), s[i+1:]
  294. default:
  295. p[j] = b
  296. j++
  297. }
  298. }
  299. return "", ""
  300. }
  301. }
  302. return "", ""
  303. }
上海开阖软件有限公司 沪ICP备12045867号-1