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.
 
 
 

300 lines
6.7 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 utils
  21. import (
  22. "fmt"
  23. "log"
  24. "math"
  25. "net"
  26. "net/http"
  27. "net/url"
  28. "os"
  29. "path"
  30. "strconv"
  31. "strings"
  32. "github.com/golang/gddo/httputil/header"
  33. )
  34. func CleanTmpFile(f *os.File) {
  35. if f != nil {
  36. err := f.Close()
  37. if err != nil {
  38. log.Printf("Error closing tmpfile: %s (%s)", err, f.Name())
  39. }
  40. err = os.Remove(f.Name())
  41. if err != nil {
  42. log.Printf("Error removing tmpfile: %s (%s)", err, f.Name())
  43. }
  44. }
  45. }
  46. func Sanitize(fileName string) string {
  47. return path.Clean(path.Base(fileName))
  48. }
  49. func ResolveURL(r *http.Request, u *url.URL) string {
  50. r.URL.Path = ""
  51. return GetURL(r).ResolveReference(u).String()
  52. }
  53. func ResolveKey(key, proxyPath string) string {
  54. if strings.HasPrefix(key, "/") {
  55. key = key[1:]
  56. }
  57. if strings.HasPrefix(key, proxyPath) {
  58. key = key[len(proxyPath):]
  59. }
  60. key = strings.Replace(key, "\\", "/", -1)
  61. return key
  62. }
  63. func ResolveWebAddress(r *http.Request, proxyPath string) string {
  64. rUrl := GetURL(r)
  65. var webAddress string
  66. if len(proxyPath) == 0 {
  67. webAddress = fmt.Sprintf("%s://%s/",
  68. rUrl.ResolveReference(rUrl).Scheme,
  69. rUrl.ResolveReference(rUrl).Host)
  70. } else {
  71. webAddress = fmt.Sprintf("%s://%s/%s",
  72. rUrl.ResolveReference(rUrl).Scheme,
  73. rUrl.ResolveReference(rUrl).Host,
  74. proxyPath)
  75. }
  76. return webAddress
  77. }
  78. func GetURL(r *http.Request) *url.URL {
  79. u, _ := url.Parse(r.URL.String())
  80. if r.TLS != nil {
  81. u.Scheme = "https"
  82. } else if proto := r.Header.Get("X-Forwarded-Proto"); proto != "" {
  83. u.Scheme = proto
  84. } else {
  85. u.Scheme = "http"
  86. }
  87. if u.Host != "" {
  88. } else if host, port, err := net.SplitHostPort(r.Host); err != nil {
  89. u.Host = r.Host
  90. } else {
  91. if port == "80" && u.Scheme == "http" {
  92. u.Host = host
  93. } else if port == "443" && u.Scheme == "https" {
  94. u.Host = host
  95. } else {
  96. u.Host = net.JoinHostPort(host, port)
  97. }
  98. }
  99. return u
  100. }
  101. func FormatNumber(format string, s int64) string {
  102. return RenderFloat(format, float64(s))
  103. }
  104. var renderFloatPrecisionMultipliers = [10]float64{
  105. 1,
  106. 10,
  107. 100,
  108. 1000,
  109. 10000,
  110. 100000,
  111. 1000000,
  112. 10000000,
  113. 100000000,
  114. 1000000000,
  115. }
  116. var renderFloatPrecisionRounders = [10]float64{
  117. 0.5,
  118. 0.05,
  119. 0.005,
  120. 0.0005,
  121. 0.00005,
  122. 0.000005,
  123. 0.0000005,
  124. 0.00000005,
  125. 0.000000005,
  126. 0.0000000005,
  127. }
  128. func RenderFloat(format string, n float64) string {
  129. // Special cases:
  130. // NaN = "NaN"
  131. // +Inf = "+Infinity"
  132. // -Inf = "-Infinity"
  133. if math.IsNaN(n) {
  134. return "NaN"
  135. }
  136. if n > math.MaxFloat64 {
  137. return "Infinity"
  138. }
  139. if n < -math.MaxFloat64 {
  140. return "-Infinity"
  141. }
  142. // default format
  143. precision := 2
  144. decimalStr := "."
  145. thousandStr := ","
  146. positiveStr := ""
  147. negativeStr := "-"
  148. if len(format) > 0 {
  149. // If there is an explicit format directive,
  150. // then default values are these:
  151. precision = 9
  152. thousandStr = ""
  153. // collect indices of meaningful formatting directives
  154. formatDirectiveChars := []rune(format)
  155. formatDirectiveIndices := make([]int, 0)
  156. for i, char := range formatDirectiveChars {
  157. if char != '#' && char != '0' {
  158. formatDirectiveIndices = append(formatDirectiveIndices, i)
  159. }
  160. }
  161. if len(formatDirectiveIndices) > 0 {
  162. // Directive at index 0:
  163. // Must be a '+'
  164. // Raise an error if not the case
  165. // index: 0123456789
  166. // +0.000,000
  167. // +000,000.0
  168. // +0000.00
  169. // +0000
  170. if formatDirectiveIndices[0] == 0 {
  171. if formatDirectiveChars[formatDirectiveIndices[0]] != '+' {
  172. panic("RenderFloat(): invalid positive sign directive")
  173. }
  174. positiveStr = "+"
  175. formatDirectiveIndices = formatDirectiveIndices[1:]
  176. }
  177. // Two directives:
  178. // First is thousands separator
  179. // Raise an error if not followed by 3-digit
  180. // 0123456789
  181. // 0.000,000
  182. // 000,000.00
  183. if len(formatDirectiveIndices) == 2 {
  184. if (formatDirectiveIndices[1] - formatDirectiveIndices[0]) != 4 {
  185. panic("RenderFloat(): thousands separator directive must be followed by 3 digit-specifiers")
  186. }
  187. thousandStr = string(formatDirectiveChars[formatDirectiveIndices[0]])
  188. formatDirectiveIndices = formatDirectiveIndices[1:]
  189. }
  190. // One directive:
  191. // Directive is decimal separator
  192. // The number of digit-specifier following the separator indicates wanted precision
  193. // 0123456789
  194. // 0.00
  195. // 000,0000
  196. if len(formatDirectiveIndices) == 1 {
  197. decimalStr = string(formatDirectiveChars[formatDirectiveIndices[0]])
  198. precision = len(formatDirectiveChars) - formatDirectiveIndices[0] - 1
  199. }
  200. }
  201. }
  202. // generate sign part
  203. var signStr string
  204. if n >= 0.000000001 {
  205. signStr = positiveStr
  206. } else if n <= -0.000000001 {
  207. signStr = negativeStr
  208. n = -n
  209. } else {
  210. signStr = ""
  211. n = 0.0
  212. }
  213. // split number into integer and fractional parts
  214. intf, fracf := math.Modf(n + renderFloatPrecisionRounders[precision])
  215. // generate integer part string
  216. intStr := strconv.Itoa(int(intf))
  217. // add thousand separator if required
  218. if len(thousandStr) > 0 {
  219. for i := len(intStr); i > 3; {
  220. i -= 3
  221. intStr = intStr[:i] + thousandStr + intStr[i:]
  222. }
  223. }
  224. // no fractional part, we can leave now
  225. if precision == 0 {
  226. return signStr + intStr
  227. }
  228. // generate fractional part
  229. fracStr := strconv.Itoa(int(fracf * renderFloatPrecisionMultipliers[precision]))
  230. // may need padding
  231. if len(fracStr) < precision {
  232. fracStr = "000000000000000"[:precision-len(fracStr)] + fracStr
  233. }
  234. return signStr + intStr + decimalStr + fracStr
  235. }
  236. // Request.RemoteAddress contains port, which we want to remove i.e.:
  237. // "[::1]:58292" => "[::1]"
  238. func IpAddrFromRemoteAddr(s string) string {
  239. idx := strings.LastIndex(s, ":")
  240. if idx == -1 {
  241. return s
  242. }
  243. return s[:idx]
  244. }
  245. func AcceptsHTML(hdr http.Header) bool {
  246. actual := header.ParseAccept(hdr, "Accept")
  247. for _, s := range actual {
  248. if s.Value == "text/html" {
  249. return true
  250. }
  251. }
  252. return false
  253. }