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.
 
 
 

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