github.com/vnforks/kid/v5@v5.22.1-0.20200408055009-b89d99c65676/utils/utils.go (about) 1 // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. 2 // See LICENSE.txt for license information. 3 4 package utils 5 6 import ( 7 "net" 8 "net/http" 9 "net/url" 10 "strings" 11 ) 12 13 func StringInSlice(a string, slice []string) bool { 14 for _, b := range slice { 15 if b == a { 16 return true 17 } 18 } 19 return false 20 } 21 22 // RemoveStringFromSlice removes the first occurrence of a from slice. 23 func RemoveStringFromSlice(a string, slice []string) []string { 24 for i, str := range slice { 25 if str == a { 26 return append(slice[:i], slice[i+1:]...) 27 } 28 } 29 return slice 30 } 31 32 // RemoveStringsFromSlice removes all occurrences of strings from slice. 33 func RemoveStringsFromSlice(slice []string, strings ...string) []string { 34 newSlice := []string{} 35 36 for _, item := range slice { 37 if !StringInSlice(item, strings) { 38 newSlice = append(newSlice, item) 39 } 40 } 41 42 return newSlice 43 } 44 45 func StringArrayIntersection(arr1, arr2 []string) []string { 46 arrMap := map[string]bool{} 47 result := []string{} 48 49 for _, value := range arr1 { 50 arrMap[value] = true 51 } 52 53 for _, value := range arr2 { 54 if arrMap[value] { 55 result = append(result, value) 56 } 57 } 58 59 return result 60 } 61 62 func RemoveDuplicatesFromStringArray(arr []string) []string { 63 result := make([]string, 0, len(arr)) 64 seen := make(map[string]bool) 65 66 for _, item := range arr { 67 if !seen[item] { 68 result = append(result, item) 69 seen[item] = true 70 } 71 } 72 73 return result 74 } 75 76 func StringSliceDiff(a, b []string) []string { 77 m := make(map[string]bool) 78 result := []string{} 79 80 for _, item := range b { 81 m[item] = true 82 } 83 84 for _, item := range a { 85 if !m[item] { 86 result = append(result, item) 87 } 88 } 89 return result 90 } 91 92 func GetIpAddress(r *http.Request, trustedProxyIPHeader []string) string { 93 address := "" 94 95 for _, proxyHeader := range trustedProxyIPHeader { 96 header := r.Header.Get(proxyHeader) 97 if len(header) > 0 { 98 addresses := strings.Fields(header) 99 if len(addresses) > 0 { 100 address = strings.TrimRight(addresses[0], ",") 101 } 102 } 103 104 if len(address) > 0 { 105 return address 106 } 107 } 108 109 if len(address) == 0 { 110 address, _, _ = net.SplitHostPort(r.RemoteAddr) 111 } 112 113 return address 114 } 115 116 func GetHostnameFromSiteURL(siteURL string) string { 117 u, err := url.Parse(siteURL) 118 if err != nil { 119 return "" 120 } 121 122 return u.Hostname() 123 }