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.
 
 
 

253 lines
6.1 KiB

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