Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 

244 рядки
5.8 KiB

  1. /*
  2. The MIT License (MIT)
  3. Copyright (c) 2014-2017 DutchCoders [https://github.com/dutchcoders/]
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. THE SOFTWARE.
  19. */
  20. package server
  21. import (
  22. "math"
  23. "net/http"
  24. "net/mail"
  25. "strconv"
  26. "strings"
  27. "github.com/golang/gddo/httputil/header"
  28. )
  29. func formatNumber(format string, s uint64) string {
  30. return RenderFloat(format, float64(s))
  31. }
  32. var renderFloatPrecisionMultipliers = [10]float64{
  33. 1,
  34. 10,
  35. 100,
  36. 1000,
  37. 10000,
  38. 100000,
  39. 1000000,
  40. 10000000,
  41. 100000000,
  42. 1000000000,
  43. }
  44. var renderFloatPrecisionRounders = [10]float64{
  45. 0.5,
  46. 0.05,
  47. 0.005,
  48. 0.0005,
  49. 0.00005,
  50. 0.000005,
  51. 0.0000005,
  52. 0.00000005,
  53. 0.000000005,
  54. 0.0000000005,
  55. }
  56. func RenderFloat(format string, n float64) string {
  57. // Special cases:
  58. // NaN = "NaN"
  59. // +Inf = "+Infinity"
  60. // -Inf = "-Infinity"
  61. if math.IsNaN(n) {
  62. return "NaN"
  63. }
  64. if n > math.MaxFloat64 {
  65. return "Infinity"
  66. }
  67. if n < -math.MaxFloat64 {
  68. return "-Infinity"
  69. }
  70. // default format
  71. precision := 2
  72. decimalStr := "."
  73. thousandStr := ","
  74. positiveStr := ""
  75. negativeStr := "-"
  76. if len(format) > 0 {
  77. // If there is an explicit format directive,
  78. // then default values are these:
  79. precision = 9
  80. thousandStr = ""
  81. // collect indices of meaningful formatting directives
  82. formatDirectiveChars := []rune(format)
  83. formatDirectiveIndices := make([]int, 0)
  84. for i, char := range formatDirectiveChars {
  85. if char != '#' && char != '0' {
  86. formatDirectiveIndices = append(formatDirectiveIndices, i)
  87. }
  88. }
  89. if len(formatDirectiveIndices) > 0 {
  90. // Directive at index 0:
  91. // Must be a '+'
  92. // Raise an error if not the case
  93. // index: 0123456789
  94. // +0.000,000
  95. // +000,000.0
  96. // +0000.00
  97. // +0000
  98. if formatDirectiveIndices[0] == 0 {
  99. if formatDirectiveChars[formatDirectiveIndices[0]] != '+' {
  100. panic("RenderFloat(): invalid positive sign directive")
  101. }
  102. positiveStr = "+"
  103. formatDirectiveIndices = formatDirectiveIndices[1:]
  104. }
  105. // Two directives:
  106. // First is thousands separator
  107. // Raise an error if not followed by 3-digit
  108. // 0123456789
  109. // 0.000,000
  110. // 000,000.00
  111. if len(formatDirectiveIndices) == 2 {
  112. if (formatDirectiveIndices[1] - formatDirectiveIndices[0]) != 4 {
  113. panic("RenderFloat(): thousands separator directive must be followed by 3 digit-specifiers")
  114. }
  115. thousandStr = string(formatDirectiveChars[formatDirectiveIndices[0]])
  116. formatDirectiveIndices = formatDirectiveIndices[1:]
  117. }
  118. // One directive:
  119. // Directive is decimal separator
  120. // The number of digit-specifier following the separator indicates wanted precision
  121. // 0123456789
  122. // 0.00
  123. // 000,0000
  124. if len(formatDirectiveIndices) == 1 {
  125. decimalStr = string(formatDirectiveChars[formatDirectiveIndices[0]])
  126. precision = len(formatDirectiveChars) - formatDirectiveIndices[0] - 1
  127. }
  128. }
  129. }
  130. // generate sign part
  131. var signStr string
  132. if n >= 0.000000001 {
  133. signStr = positiveStr
  134. } else if n <= -0.000000001 {
  135. signStr = negativeStr
  136. n = -n
  137. } else {
  138. signStr = ""
  139. n = 0.0
  140. }
  141. // split number into integer and fractional parts
  142. intf, fracf := math.Modf(n + renderFloatPrecisionRounders[precision])
  143. // generate integer part string
  144. intStr := strconv.Itoa(int(intf))
  145. // add thousand separator if required
  146. if len(thousandStr) > 0 {
  147. for i := len(intStr); i > 3; {
  148. i -= 3
  149. intStr = intStr[:i] + thousandStr + intStr[i:]
  150. }
  151. }
  152. // no fractional part, we can leave now
  153. if precision == 0 {
  154. return signStr + intStr
  155. }
  156. // generate fractional part
  157. fracStr := strconv.Itoa(int(fracf * renderFloatPrecisionMultipliers[precision]))
  158. // may need padding
  159. if len(fracStr) < precision {
  160. fracStr = "000000000000000"[:precision-len(fracStr)] + fracStr
  161. }
  162. return signStr + intStr + decimalStr + fracStr
  163. }
  164. func RenderInteger(format string, n int) string {
  165. return RenderFloat(format, float64(n))
  166. }
  167. // Request.RemoteAddress contains port, which we want to remove i.e.:
  168. // "[::1]:58292" => "[::1]"
  169. func ipAddrFromRemoteAddr(s string) string {
  170. idx := strings.LastIndex(s, ":")
  171. if idx == -1 {
  172. return s
  173. }
  174. return s[:idx]
  175. }
  176. func getIPAddress(r *http.Request) string {
  177. hdr := r.Header
  178. hdrRealIP := hdr.Get("X-Real-Ip")
  179. hdrForwardedFor := hdr.Get("X-Forwarded-For")
  180. if hdrRealIP == "" && hdrForwardedFor == "" {
  181. return ipAddrFromRemoteAddr(r.RemoteAddr)
  182. }
  183. if hdrForwardedFor != "" {
  184. // X-Forwarded-For is potentially a list of addresses separated with ","
  185. parts := strings.Split(hdrForwardedFor, ",")
  186. for i, p := range parts {
  187. parts[i] = strings.TrimSpace(p)
  188. }
  189. // TODO: should return first non-local address
  190. return parts[0]
  191. }
  192. return hdrRealIP
  193. }
  194. func encodeRFC2047(s string) string {
  195. // use mail's rfc2047 to encode any string
  196. addr := mail.Address{
  197. Name: s,
  198. Address: "",
  199. }
  200. return strings.Trim(addr.String(), " <>")
  201. }
  202. func acceptsHTML(hdr http.Header) bool {
  203. actual := header.ParseAccept(hdr, "Accept")
  204. for _, s := range actual {
  205. if s.Value == "text/html" {
  206. return (true)
  207. }
  208. }
  209. return (false)
  210. }