util.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. package common
  2. import (
  3. "bytes"
  4. "encoding/base64"
  5. "encoding/binary"
  6. "github.com/cnlh/nps/lib/crypt"
  7. "io/ioutil"
  8. "net"
  9. "net/http"
  10. "os"
  11. "regexp"
  12. "strconv"
  13. "strings"
  14. )
  15. //Judging Compression Mode
  16. func GetCompressType(compress string) (int, int) {
  17. switch compress {
  18. case "":
  19. return COMPRESS_NONE_DECODE, COMPRESS_NONE_ENCODE
  20. case "snappy":
  21. return COMPRESS_SNAPY_DECODE, COMPRESS_SNAPY_ENCODE
  22. default:
  23. return COMPRESS_NONE_DECODE, COMPRESS_NONE_ENCODE
  24. }
  25. return COMPRESS_NONE_DECODE, COMPRESS_NONE_ENCODE
  26. }
  27. //Get the corresponding IP address through domain name
  28. func GetHostByName(hostname string) string {
  29. if !DomainCheck(hostname) {
  30. return hostname
  31. }
  32. ips, _ := net.LookupIP(hostname)
  33. if ips != nil {
  34. for _, v := range ips {
  35. if v.To4() != nil {
  36. return v.String()
  37. }
  38. }
  39. }
  40. return ""
  41. }
  42. //Check the legality of domain
  43. func DomainCheck(domain string) bool {
  44. var match bool
  45. IsLine := "^((http://)|(https://))?([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,6}(/)"
  46. NotLine := "^((http://)|(https://))?([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,6}"
  47. match, _ = regexp.MatchString(IsLine, domain)
  48. if !match {
  49. match, _ = regexp.MatchString(NotLine, domain)
  50. }
  51. return match
  52. }
  53. //Check if the Request request is validated
  54. func CheckAuth(r *http.Request, user, passwd string) bool {
  55. s := strings.SplitN(r.Header.Get("Authorization"), " ", 2)
  56. if len(s) != 2 {
  57. return false
  58. }
  59. b, err := base64.StdEncoding.DecodeString(s[1])
  60. if err != nil {
  61. return false
  62. }
  63. pair := strings.SplitN(string(b), ":", 2)
  64. if len(pair) != 2 {
  65. return false
  66. }
  67. return pair[0] == user && pair[1] == passwd
  68. }
  69. //get bool by str
  70. func GetBoolByStr(s string) bool {
  71. switch s {
  72. case "1", "true":
  73. return true
  74. }
  75. return false
  76. }
  77. //get str by bool
  78. func GetStrByBool(b bool) string {
  79. if b {
  80. return "1"
  81. }
  82. return "0"
  83. }
  84. //int
  85. func GetIntNoErrByStr(str string) int {
  86. i, _ := strconv.Atoi(str)
  87. return i
  88. }
  89. //Get verify value
  90. func Getverifyval(vkey string) string {
  91. return crypt.Md5(vkey)
  92. }
  93. //Change headers and host of request
  94. func ChangeHostAndHeader(r *http.Request, host string, header string, addr string) {
  95. if host != "" {
  96. r.Host = host
  97. }
  98. if header != "" {
  99. h := strings.Split(header, "\n")
  100. for _, v := range h {
  101. hd := strings.Split(v, ":")
  102. if len(hd) == 2 {
  103. r.Header.Set(hd[0], hd[1])
  104. }
  105. }
  106. }
  107. addr = strings.Split(addr, ":")[0]
  108. r.Header.Set("X-Forwarded-For", addr)
  109. r.Header.Set("X-Real-IP", addr)
  110. }
  111. //Read file content by file path
  112. func ReadAllFromFile(filePath string) ([]byte, error) {
  113. f, err := os.Open(filePath)
  114. if err != nil {
  115. return nil, err
  116. }
  117. return ioutil.ReadAll(f)
  118. }
  119. // FileExists reports whether the named file or directory exists.
  120. func FileExists(name string) bool {
  121. if _, err := os.Stat(name); err != nil {
  122. if os.IsNotExist(err) {
  123. return false
  124. }
  125. }
  126. return true
  127. }
  128. //Judge whether the TCP port can open normally
  129. func TestTcpPort(port int) bool {
  130. l, err := net.ListenTCP("tcp", &net.TCPAddr{net.ParseIP("0.0.0.0"), port, ""})
  131. defer func() {
  132. if l != nil {
  133. l.Close()
  134. }
  135. }()
  136. if err != nil {
  137. return false
  138. }
  139. return true
  140. }
  141. //Judge whether the UDP port can open normally
  142. func TestUdpPort(port int) bool {
  143. l, err := net.ListenUDP("udp", &net.UDPAddr{net.ParseIP("0.0.0.0"), port, ""})
  144. defer func() {
  145. if l != nil {
  146. l.Close()
  147. }
  148. }()
  149. if err != nil {
  150. return false
  151. }
  152. return true
  153. }
  154. //Write length and individual byte data
  155. //Length prevents sticking
  156. //# Characters are used to separate data
  157. func BinaryWrite(raw *bytes.Buffer, v ...string) {
  158. buffer := new(bytes.Buffer)
  159. var l int32
  160. for _, v := range v {
  161. l += int32(len([]byte(v))) + int32(len([]byte(CONN_DATA_SEQ)))
  162. binary.Write(buffer, binary.LittleEndian, []byte(v))
  163. binary.Write(buffer, binary.LittleEndian, []byte(CONN_DATA_SEQ))
  164. }
  165. binary.Write(raw, binary.LittleEndian, l)
  166. binary.Write(raw, binary.LittleEndian, buffer.Bytes())
  167. }
  168. func InStrArr(arr []string, val string) bool {
  169. for _, v := range arr {
  170. if v == val {
  171. return true
  172. }
  173. }
  174. return false
  175. }
  176. func InIntArr(arr []int, val int) bool {
  177. for _, v := range arr {
  178. if v == val {
  179. return true
  180. }
  181. }
  182. return false
  183. }
  184. func GetPorts(p string) []int {
  185. var ps []int
  186. arr := strings.Split(p, ",")
  187. for _, v := range arr {
  188. fw := strings.Split(v, "-")
  189. if len(fw) == 2 {
  190. if IsPort(fw[0]) && IsPort(fw[1]) {
  191. start, _ := strconv.Atoi(fw[0])
  192. end, _ := strconv.Atoi(fw[1])
  193. for i := start; i <= end; i++ {
  194. ps = append(ps, i)
  195. }
  196. } else {
  197. continue
  198. }
  199. } else if IsPort(v) {
  200. p, _ := strconv.Atoi(v)
  201. ps = append(ps, p)
  202. }
  203. }
  204. return ps
  205. }
  206. func IsPort(p string) bool {
  207. pi, err := strconv.Atoi(p)
  208. if err != nil {
  209. return false
  210. }
  211. if pi > 65536 || pi < 1 {
  212. return false
  213. }
  214. return true
  215. }
  216. func FormatAddress(s string) string {
  217. if strings.Contains(s, ":") {
  218. return s
  219. }
  220. return "127.0.0.1:" + s
  221. }
  222. func GetIpByAddr(addr string) string {
  223. arr := strings.Split(addr, ":")
  224. return arr[0]
  225. }