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.
 
 
 

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