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.
 
 
 

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