common.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. package utility
  2. import (
  3. "crawler/config"
  4. "encoding/json"
  5. "fmt"
  6. "github.com/gin-gonic/gin"
  7. "log"
  8. "math/rand"
  9. "net"
  10. "net/http"
  11. "os"
  12. "regexp"
  13. "strings"
  14. "time"
  15. )
  16. // 패키지 호출 시 실행
  17. func SetEnviron() {
  18. // 변수화 대상 설정 파일
  19. var configFiles = [...]string{
  20. config.ENV_PATH, config.CONFIG_PATH_DATABASE, config.CONFIG_PATH_MOVIE, config.CONFIG_PATH_G2A,
  21. }
  22. // json 설정 파일을 읽어들인 후 변수화
  23. for _, file := range configFiles {
  24. SetValueFromJsonFile(file)
  25. }
  26. // 현재 개발환경 변수 확인 (local, dev)
  27. var DEVELOPER_ENV = DeveloperEnv()
  28. if DEVELOPER_ENV == "" {
  29. DEVELOPER_ENV = config.Env.DeveloperEnv
  30. }
  31. if os.Setenv(config.EnvKey, DEVELOPER_ENV) == nil {
  32. config.Env.DeveloperEnv = DEVELOPER_ENV
  33. }
  34. }
  35. // json 파일에서 값 추출 후 변수화
  36. func SetValueFromJsonFile(filePath string) {
  37. file, err := os.Open(filePath)
  38. defer func() {
  39. err := file.Close()
  40. if err != nil {
  41. log.Fatalln(err)
  42. }
  43. }()
  44. Check(err, nil)
  45. decoder := json.NewDecoder(file)
  46. switch filePath {
  47. case config.ENV_PATH:
  48. err = decoder.Decode(&config.Env)
  49. case config.CONFIG_PATH_DATABASE:
  50. err = decoder.Decode(&config.DB)
  51. case config.CONFIG_PATH_MOVIE:
  52. err = decoder.Decode(&config.Movie)
  53. case config.CONFIG_PATH_G2A:
  54. err = decoder.Decode(&config.G2A)
  55. }
  56. Check(err, nil)
  57. }
  58. // Gin 디버그 모드 사용할 것인가 여부
  59. func SetDebug() {
  60. if config.Env.IsDebug {
  61. gin.SetMode(gin.DebugMode)
  62. } else {
  63. gin.SetMode(gin.ReleaseMode)
  64. }
  65. }
  66. // 오류 확인
  67. func Check(err error, path interface{}) {
  68. if err != nil {
  69. if path == nil || path == "" {
  70. path = "./log/error.txt"
  71. }
  72. logFile, err := os.OpenFile(path.(string), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
  73. if err != nil {
  74. panic(err)
  75. }
  76. defer logFile.Close()
  77. logger := log.New(logFile, "INFO: ", log.Ldate|log.Ltime|log.Lshortfile)
  78. logger.Printf("%s\n", err.Error())
  79. }
  80. }
  81. // 설정된 개발 환경변수 조회
  82. func DeveloperEnv() string {
  83. return strings.ToLower(os.Getenv(config.EnvKey)) // 소문자로 변환
  84. }
  85. // 시작시간으로 부터 소요시간(초)
  86. func GetDurationInMillseconds(start time.Time) float64 {
  87. end := time.Now()
  88. duration := end.Sub(start)
  89. milliseconds := float64(duration) / float64(time.Millisecond)
  90. rounded := float64(int(milliseconds*100+.5)) / 100
  91. return rounded
  92. }
  93. func IpAddrFromRemoteAddr(s string) string {
  94. idx := strings.LastIndex(s, ":")
  95. if idx == -1 {
  96. return s
  97. }
  98. return s[:idx]
  99. }
  100. // 현재 요청 IP
  101. func GetClientIP(c *gin.Context) string {
  102. // first check the X-Forwarded-For header
  103. requester := c.Request.Header.Get("X-Forwarded-For")
  104. // if empty, check the Real-IP header
  105. if len(requester) == 0 {
  106. requester = c.Request.Header.Get("X-Real-IP")
  107. }
  108. // if the requester is still empty, use the hard-coded address from the socket
  109. if len(requester) == 0 {
  110. requester = c.Request.RemoteAddr
  111. }
  112. // if requester is a comma delimited list, take the first one
  113. // (this happens when proxied via elastic load balancer then again through nginx)
  114. if strings.Contains(requester, ",") {
  115. requester = strings.Split(requester, ",")[0]
  116. }
  117. return requester
  118. }
  119. // 현재 서버 IP
  120. func GetLocalIP() string {
  121. addrs, err := net.InterfaceAddrs()
  122. if err != nil {
  123. return ""
  124. }
  125. for _, address := range addrs {
  126. // check the address type and if it is not a loopback the display it
  127. if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
  128. if ipnet.IP.To4() != nil {
  129. return ipnet.IP.String()
  130. }
  131. }
  132. }
  133. return ""
  134. }
  135. func RequestGetRemoteAddress(r *http.Request) string {
  136. hdr := r.Header
  137. hdrRealIP := hdr.Get("X-Real-Ip")
  138. hdrForwardedFor := hdr.Get("X-Forwarded-For")
  139. if hdrRealIP == "" && hdrForwardedFor == "" {
  140. return IpAddrFromRemoteAddr(r.RemoteAddr)
  141. }
  142. if hdrForwardedFor != "" {
  143. // X-Forwarded-For is potentially a list of addresses separated with ","
  144. parts := strings.Split(hdrForwardedFor, ",")
  145. for i, p := range parts {
  146. parts[i] = strings.TrimSpace(p)
  147. }
  148. // TODO: should return first non-local address
  149. return parts[0]
  150. }
  151. return hdrRealIP
  152. }
  153. // 사용자 useragent 조회
  154. func UserAgent(w http.ResponseWriter, r *http.Request) {
  155. ua := r.UserAgent() //<---- simpler and faster!
  156. fmt.Printf("user agent is: %s \n", ua)
  157. w.Write([]byte("user agent is " + ua))
  158. }
  159. // 데이터 단위 변환
  160. func ByteSize(bytes uint64) string {
  161. unit := ""
  162. value := float32(bytes)
  163. switch {
  164. case bytes >= config.TERABYTE:
  165. unit = "T"
  166. value = value / config.TERABYTE
  167. case bytes >= config.GIGABYTE:
  168. unit = "G"
  169. value = value / config.GIGABYTE
  170. case bytes >= config.MEGABYTE:
  171. unit = "M"
  172. value = value / config.MEGABYTE
  173. case bytes >= config.KILOBYTE:
  174. unit = "K"
  175. value = value / config.KILOBYTE
  176. case bytes >= config.BYTE:
  177. unit = "B"
  178. case bytes == 0:
  179. return "0"
  180. }
  181. stringValue := fmt.Sprintf("%.1f", value)
  182. stringValue = strings.TrimSuffix(stringValue, ".0")
  183. return fmt.Sprintf("%s%s", stringValue, unit)
  184. }
  185. // inArray
  186. func Find(slice []string, val string) (int, bool) {
  187. for i, item := range slice {
  188. if item == val {
  189. return i, true
  190. }
  191. }
  192. return -1, false
  193. }
  194. const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  195. func RandomString() string {
  196. b := make([]byte, rand.Intn(10)+10)
  197. for i := range b {
  198. b[i] = letterBytes[rand.Intn(len(letterBytes))]
  199. }
  200. return string(b)
  201. }
  202. // 특수문자 제거
  203. func RemoveSpecialChar(s string) string {
  204. return strings.TrimSpace(regexp.MustCompile(`[\{\}\[\]\/?.,;:|\)*~!^\-_+<>@\#$%&\\\=\(\'\"\n\r]+`).ReplaceAllString(s, ""))
  205. }