utils.go 5.9 KB

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