utils.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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. "net/mail"
  28. "strconv"
  29. "strings"
  30. "github.com/aws/aws-sdk-go/aws"
  31. "github.com/aws/aws-sdk-go/aws/credentials"
  32. "github.com/aws/aws-sdk-go/aws/session"
  33. "github.com/golang/gddo/httputil/header"
  34. )
  35. func getAwsSession(accessKey, secretKey, region, endpoint string, forcePathStyle bool) *session.Session {
  36. return session.Must(session.NewSession(&aws.Config{
  37. Region: aws.String(region),
  38. Endpoint: aws.String(endpoint),
  39. Credentials: credentials.NewStaticCredentials(accessKey, secretKey, ""),
  40. S3ForcePathStyle: aws.Bool(forcePathStyle),
  41. }))
  42. }
  43. func formatNumber(format string, s uint64) string {
  44. return renderFloat(format, float64(s))
  45. }
  46. var renderFloatPrecisionMultipliers = [10]float64{
  47. 1,
  48. 10,
  49. 100,
  50. 1000,
  51. 10000,
  52. 100000,
  53. 1000000,
  54. 10000000,
  55. 100000000,
  56. 1000000000,
  57. }
  58. var renderFloatPrecisionRounders = [10]float64{
  59. 0.5,
  60. 0.05,
  61. 0.005,
  62. 0.0005,
  63. 0.00005,
  64. 0.000005,
  65. 0.0000005,
  66. 0.00000005,
  67. 0.000000005,
  68. 0.0000000005,
  69. }
  70. func renderFloat(format string, n float64) string {
  71. // Special cases:
  72. // NaN = "NaN"
  73. // +Inf = "+Infinity"
  74. // -Inf = "-Infinity"
  75. if math.IsNaN(n) {
  76. return "NaN"
  77. }
  78. if n > math.MaxFloat64 {
  79. return "Infinity"
  80. }
  81. if n < -math.MaxFloat64 {
  82. return "-Infinity"
  83. }
  84. // default format
  85. precision := 2
  86. decimalStr := "."
  87. thousandStr := ","
  88. positiveStr := ""
  89. negativeStr := "-"
  90. if len(format) > 0 {
  91. // If there is an explicit format directive,
  92. // then default values are these:
  93. precision = 9
  94. thousandStr = ""
  95. // collect indices of meaningful formatting directives
  96. formatDirectiveChars := []rune(format)
  97. formatDirectiveIndices := make([]int, 0)
  98. for i, char := range formatDirectiveChars {
  99. if char != '#' && char != '0' {
  100. formatDirectiveIndices = append(formatDirectiveIndices, i)
  101. }
  102. }
  103. if len(formatDirectiveIndices) > 0 {
  104. // Directive at index 0:
  105. // Must be a '+'
  106. // Raise an error if not the case
  107. // index: 0123456789
  108. // +0.000,000
  109. // +000,000.0
  110. // +0000.00
  111. // +0000
  112. if formatDirectiveIndices[0] == 0 {
  113. if formatDirectiveChars[formatDirectiveIndices[0]] != '+' {
  114. panic("renderFloat(): invalid positive sign directive")
  115. }
  116. positiveStr = "+"
  117. formatDirectiveIndices = formatDirectiveIndices[1:]
  118. }
  119. // Two directives:
  120. // First is thousands separator
  121. // Raise an error if not followed by 3-digit
  122. // 0123456789
  123. // 0.000,000
  124. // 000,000.00
  125. if len(formatDirectiveIndices) == 2 {
  126. if (formatDirectiveIndices[1] - formatDirectiveIndices[0]) != 4 {
  127. panic("renderFloat(): thousands separator directive must be followed by 3 digit-specifiers")
  128. }
  129. thousandStr = string(formatDirectiveChars[formatDirectiveIndices[0]])
  130. formatDirectiveIndices = formatDirectiveIndices[1:]
  131. }
  132. // One directive:
  133. // Directive is decimal separator
  134. // The number of digit-specifier following the separator indicates wanted precision
  135. // 0123456789
  136. // 0.00
  137. // 000,0000
  138. if len(formatDirectiveIndices) == 1 {
  139. decimalStr = string(formatDirectiveChars[formatDirectiveIndices[0]])
  140. precision = len(formatDirectiveChars) - formatDirectiveIndices[0] - 1
  141. }
  142. }
  143. }
  144. // generate sign part
  145. var signStr string
  146. if n >= 0.000000001 {
  147. signStr = positiveStr
  148. } else if n <= -0.000000001 {
  149. signStr = negativeStr
  150. n = -n
  151. } else {
  152. signStr = ""
  153. n = 0.0
  154. }
  155. // split number into integer and fractional parts
  156. intf, fracf := math.Modf(n + renderFloatPrecisionRounders[precision])
  157. // generate integer part string
  158. intStr := strconv.Itoa(int(intf))
  159. // add thousand separator if required
  160. if len(thousandStr) > 0 {
  161. for i := len(intStr); i > 3; {
  162. i -= 3
  163. intStr = intStr[:i] + thousandStr + intStr[i:]
  164. }
  165. }
  166. // no fractional part, we can leave now
  167. if precision == 0 {
  168. return signStr + intStr
  169. }
  170. // generate fractional part
  171. fracStr := strconv.Itoa(int(fracf * renderFloatPrecisionMultipliers[precision]))
  172. // may need padding
  173. if len(fracStr) < precision {
  174. fracStr = "000000000000000"[:precision-len(fracStr)] + fracStr
  175. }
  176. return signStr + intStr + decimalStr + fracStr
  177. }
  178. func renderInteger(format string, n int) string {
  179. return renderFloat(format, float64(n))
  180. }
  181. // Request.RemoteAddress contains port, which we want to remove i.e.:
  182. // "[::1]:58292" => "[::1]"
  183. func ipAddrFromRemoteAddr(s string) string {
  184. idx := strings.LastIndex(s, ":")
  185. if idx == -1 {
  186. return s
  187. }
  188. return s[:idx]
  189. }
  190. func getIPAddress(r *http.Request) string {
  191. hdr := r.Header
  192. hdrRealIP := hdr.Get("X-Real-Ip")
  193. hdrForwardedFor := hdr.Get("X-Forwarded-For")
  194. if hdrRealIP == "" && hdrForwardedFor == "" {
  195. return ipAddrFromRemoteAddr(r.RemoteAddr)
  196. }
  197. if hdrForwardedFor != "" {
  198. // X-Forwarded-For is potentially a list of addresses separated with ","
  199. parts := strings.Split(hdrForwardedFor, ",")
  200. for i, p := range parts {
  201. parts[i] = strings.TrimSpace(p)
  202. }
  203. // TODO: should return first non-local address
  204. return parts[0]
  205. }
  206. return hdrRealIP
  207. }
  208. func encodeRFC2047(s string) string {
  209. // use mail's rfc2047 to encode any string
  210. addr := mail.Address{
  211. Name: s,
  212. Address: "",
  213. }
  214. return strings.Trim(addr.String(), " <>")
  215. }
  216. func acceptsHTML(hdr http.Header) bool {
  217. actual := header.ParseAccept(hdr, "Accept")
  218. for _, s := range actual {
  219. if s.Value == "text/html" {
  220. return (true)
  221. }
  222. }
  223. return (false)
  224. }
  225. func formatSize(size int64) string {
  226. sizeFloat := float64(size)
  227. base := math.Log(sizeFloat) / math.Log(1024)
  228. sizeOn := math.Pow(1024, base-math.Floor(base))
  229. var round float64
  230. pow := math.Pow(10, float64(2))
  231. digit := pow * sizeOn
  232. round = math.Floor(digit)
  233. newVal := round / pow
  234. var suffixes [5]string
  235. suffixes[0] = "B"
  236. suffixes[1] = "KB"
  237. suffixes[2] = "MB"
  238. suffixes[3] = "GB"
  239. suffixes[4] = "TB"
  240. getSuffix := suffixes[int(math.Floor(base))]
  241. return fmt.Sprintf("%s %s", strconv.FormatFloat(newVal, 'f', -1, 64), getSuffix)
  242. }
  243. func CloseCheck(f func() error) {
  244. if err := f(); err != nil {
  245. fmt.Println("Received close error:", err)
  246. }
  247. }