util.go 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. package common
  2. import (
  3. "bytes"
  4. "encoding/base64"
  5. "encoding/binary"
  6. "github.com/cnlh/nps/lib/crypt"
  7. "github.com/cnlh/nps/lib/lg"
  8. "io/ioutil"
  9. "net"
  10. "net/http"
  11. "os"
  12. "regexp"
  13. "strconv"
  14. "strings"
  15. )
  16. //Judging Compression Mode
  17. func GetCompressType(compress string) (int, int) {
  18. switch compress {
  19. case "":
  20. return COMPRESS_NONE_DECODE, COMPRESS_NONE_ENCODE
  21. case "snappy":
  22. return COMPRESS_SNAPY_DECODE, COMPRESS_SNAPY_ENCODE
  23. default:
  24. lg.Fatalln("数据压缩格式错误")
  25. }
  26. return COMPRESS_NONE_DECODE, COMPRESS_NONE_ENCODE
  27. }
  28. //Get the corresponding IP address through domain name
  29. func GetHostByName(hostname string) string {
  30. if !DomainCheck(hostname) {
  31. return hostname
  32. }
  33. ips, _ := net.LookupIP(hostname)
  34. if ips != nil {
  35. for _, v := range ips {
  36. if v.To4() != nil {
  37. return v.String()
  38. }
  39. }
  40. }
  41. return ""
  42. }
  43. //Check the legality of domain
  44. func DomainCheck(domain string) bool {
  45. var match bool
  46. IsLine := "^((http://)|(https://))?([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,6}(/)"
  47. NotLine := "^((http://)|(https://))?([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,6}"
  48. match, _ = regexp.MatchString(IsLine, domain)
  49. if !match {
  50. match, _ = regexp.MatchString(NotLine, domain)
  51. }
  52. return match
  53. }
  54. //Check if the Request request is validated
  55. func CheckAuth(r *http.Request, user, passwd string) bool {
  56. s := strings.SplitN(r.Header.Get("Authorization"), " ", 2)
  57. if len(s) != 2 {
  58. return false
  59. }
  60. b, err := base64.StdEncoding.DecodeString(s[1])
  61. if err != nil {
  62. return false
  63. }
  64. pair := strings.SplitN(string(b), ":", 2)
  65. if len(pair) != 2 {
  66. return false
  67. }
  68. return pair[0] == user && pair[1] == passwd
  69. }
  70. //get bool by str
  71. func GetBoolByStr(s string) bool {
  72. switch s {
  73. case "1", "true":
  74. return true
  75. }
  76. return false
  77. }
  78. //get str by bool
  79. func GetStrByBool(b bool) string {
  80. if b {
  81. return "1"
  82. }
  83. return "0"
  84. }
  85. //int
  86. func GetIntNoErrByStr(str string) int {
  87. i, _ := strconv.Atoi(str)
  88. return i
  89. }
  90. //Get verify value
  91. func Getverifyval(vkey string) string {
  92. return crypt.Md5(vkey)
  93. }
  94. //Change headers and host of request
  95. func ChangeHostAndHeader(r *http.Request, host string, header string, addr string) {
  96. if host != "" {
  97. r.Host = host
  98. }
  99. if header != "" {
  100. h := strings.Split(header, "\n")
  101. for _, v := range h {
  102. hd := strings.Split(v, ":")
  103. if len(hd) == 2 {
  104. r.Header.Set(hd[0], hd[1])
  105. }
  106. }
  107. }
  108. addr = strings.Split(addr, ":")[0]
  109. r.Header.Set("X-Forwarded-For", addr)
  110. r.Header.Set("X-Real-IP", addr)
  111. }
  112. //Read file content by file path
  113. func ReadAllFromFile(filePath string) ([]byte, error) {
  114. f, err := os.Open(filePath)
  115. if err != nil {
  116. return nil, err
  117. }
  118. return ioutil.ReadAll(f)
  119. }
  120. // FileExists reports whether the named file or directory exists.
  121. func FileExists(name string) bool {
  122. if _, err := os.Stat(name); err != nil {
  123. if os.IsNotExist(err) {
  124. return false
  125. }
  126. }
  127. return true
  128. }
  129. //Judge whether the TCP port can open normally
  130. func TestTcpPort(port int) bool {
  131. l, err := net.ListenTCP("tcp", &net.TCPAddr{net.ParseIP("0.0.0.0"), port, ""})
  132. defer l.Close()
  133. if err != nil {
  134. return false
  135. }
  136. return true
  137. }
  138. //Judge whether the UDP port can open normally
  139. func TestUdpPort(port int) bool {
  140. l, err := net.ListenUDP("udp", &net.UDPAddr{net.ParseIP("0.0.0.0"), port, ""})
  141. defer l.Close()
  142. if err != nil {
  143. return false
  144. }
  145. return true
  146. }
  147. //Write length and individual byte data
  148. //Length prevents sticking
  149. //# Characters are used to separate data
  150. func BinaryWrite(raw *bytes.Buffer, v ...string) {
  151. buffer := new(bytes.Buffer)
  152. var l int32
  153. for _, v := range v {
  154. l += int32(len([]byte(v))) + int32(len([]byte("#")))
  155. binary.Write(buffer, binary.LittleEndian, []byte(v))
  156. binary.Write(buffer, binary.LittleEndian, []byte("#"))
  157. }
  158. binary.Write(raw, binary.LittleEndian, buffer.Bytes())
  159. }