The script that I am using has a variable named SourceIP. I have some static lists of IP Ranges for VPN Pools. How can I set up a searching logic to determine in which IP Pool the Source IP resides?
Here are the example details:
SourceIP = 15.15.7.49
VPNpool1 = 15.15.1.0 - 15.15.9.255
VPNPool2 = 15.15.10.0 - 15.15.19.255
Normally when I want to see if an value is in a list of values I use If VARIABLE contains ITEM1,ITEM2,ITEMn. This method won't work for VPN Pool ranges because I would have to list out every IP. I am hoping someone knows how I can make this work.
Perhaps something like:
If SourceIP in VPNPool1
{
MsgBox The SourceIP is from VPNPool1
}
If SourceIP in VPNPool12
{
MsgBox The SourceIP is from VPNPool2
}
Else
{
MsgBox The SourceIP is not in a VPNPool.
}
Try this. Make sure you have the latest AutoHotkey version which supports objects.
IP := "15.15.9.254"
Start := "15.15.1.0"
End := "15.15.9.255"
if InIPRange(IP, Start, End)
msgbox yes
else
msgbox no
InIPRange(strIP, strStart, strEnd) {
arrIPRanges := {}
loop, parse, strStart, .
arrIPRanges[A_Index, A_LoopField] := A_LoopField
loop, parse, strEnd, .
arrIPRanges[A_Index, A_LoopField] := A_LoopField
loop, parse, strIP, .
{
if arrIPRanges[A_Index].MinIndex() > A_LoopField
return false
if arrIPRanges[A_Index].MaxIndex() < A_LoopField
return false
}
return true
}
Related
How to parse PutMetricData Sample Request as show below.
I want to parse all the MetricData and stores the values in a struct in golang.
https://monitoring.&api-domain;/doc/2010-08-01/
?Action=PutMetricData
&Version=2010-08-01
&Namespace=TestNamespace
&MetricData.member.1.MetricName=buffers
&MetricData.member.1.Unit=Bytes
&MetricData.member.1.Value=231434333
&MetricData.member.1.Dimensions.member.1.Name=InstanceID
&MetricData.member.1.Dimensions.member.1.Value=i-aaba32d4
&MetricData.member.1.Dimensions.member.2.Name=InstanceType
&MetricData.member.1.Dimensions.member.2.Value=m1.small
&MetricData.member.2.MetricName=latency
&MetricData.member.2.Unit=Milliseconds
&MetricData.member.2.Value=23
&MetricData.member.2.Dimensions.member.1.Name=InstanceID
&MetricData.member.2.Dimensions.member.1.Value=i-aaba32d4
&MetricData.member.2.Dimensions.member.2.Name=InstanceType
&MetricData.member.2.Dimensions.member.2.Value=m1.small**
&AUTHPARAMS
Not able to understand this is in which format and how to parse it. Any library available to generate and parse this kind of formatted message?
If you remove the newlines that is a URL. Start with url.Parse, then use the Query() function to get access to the url parameters:
func main() {
var input = `https://monitoring.&api-domain;/doc/2010-08-01/
?Action=PutMetricData
&Version=2010-08-01
&Namespace=TestNamespace
&MetricData.member.1.MetricName=buffers
&MetricData.member.1.Unit=Bytes
&MetricData.member.1.Value=231434333
&MetricData.member.1.Dimensions.member.1.Name=InstanceID
&MetricData.member.1.Dimensions.member.1.Value=i-aaba32d4
&MetricData.member.1.Dimensions.member.2.Name=InstanceType
&MetricData.member.1.Dimensions.member.2.Value=m1.small
&MetricData.member.2.MetricName=latency
&MetricData.member.2.Unit=Milliseconds
&MetricData.member.2.Value=23
&MetricData.member.2.Dimensions.member.1.Name=InstanceID
&MetricData.member.2.Dimensions.member.1.Value=i-aaba32d4
&MetricData.member.2.Dimensions.member.2.Name=InstanceType
&MetricData.member.2.Dimensions.member.2.Value=m1.small**
&AUTHPARAMS`
// possibly also needs to replace \r
input = strings.ReplaceAll(input, "\n", "")
uri, err := url.Parse(input)
if err != nil {
log.Fatal(err)
}
for key, val := range uri.Query() {
fmt.Println(key, val)
}
}
Playground
From here on out it's up to you how you want the target struct to look like.
I am building REST APIs, using Lambda and DynamoDB in GO.
I need to query the data based on multiple filters.
The number of filters can be varying based on the number of query parameters user has provided, while calling the REST API.
As per the below post, I had developed the code to add multiple conditions.
AWS SDK for Go - DynamoDb - Add multiple conditions to FilterExpression
But when I invoke the function, I get below error, in the logs.-
buildTree error: unset parameter: ConditionBuilder
The Filter expression is not applied and the scan returns all the results.
Here is the code snippet.
for queryParam, queryParamValue := range searchParams {
fmt.Println("queryParam:", queryParam, "=>", "queryParamValue:", queryParamValue)
if queryParam == “param1” {
param1Condition = expression.Name(“param1”).Equal(expression.Value(queryParamValue))
}
if queryParam == “param2” {
param2Condition = expression.Name(“param2”).Equal(expression.Value(queryParamValue))
}
}
sampleExpr, errSample := expression.NewBuilder().
WithCondition(param1Condition.Or(param2Condition)).
Build()
if errSample != nil {
fmt.Println("Error in building Sample Expr ", errSample)
} else {
fmt.Println("sampleExpr ", sampleExpr)
}
input := &dynamodb.ScanInput{
ExpressionAttributeNames: sampleExpr.Names(),
ExpressionAttributeValues: sampleExpr.Values(),
FilterExpression: sampleExpr.Filter(),
TableName: aws.String(deviceInfotable),
}
But if I create the expression in different way, it works.
filt := expression.Name("param1").Equal(expression.Value("valu1")).Or(expression.Name("param2").Equal(expression.Value("value2")))
ConditionBuilder has mode field
type ConditionBuilder struct {
operandList []OperandBuilder
conditionList []ConditionBuilder
mode conditionMode
}
The zero value of mode is unsetCond. When build condition, unsetCond raises the error.
https://github.com/aws/aws-sdk-go/blob/7798c2e0edc02ba058f7672d32f4ebf6603b5fc6/service/dynamodb/expression/condition.go#L1415
case unsetCond:
return exprNode{}, newUnsetParameterError("buildTree", "ConditionBuilder")
In your code, if queryParam != “param1” and queryParam != “param2”, the param1Condition and param2Condition is zero value of ConditionBuilder, which fails on build.
In the code sample below, I use regex to extract the subdomain name from a given URL. This sample works, but I don't think I've done it correctly at the point where I compile the regex, mainly where I insert the 'virtualHost' variable. Any suggestions?
package main
import (
"fmt"
"regexp"
)
var (
virtualHost string
domainRegex *regexp.Regexp
)
func extractSubdomain(host string) string {
matches := domainRegex.FindStringSubmatch(host)
if matches != nil && len(matches) > 1 {
return matches[1]
}
return ""
}
func init() {
// virtualHost = os.GetEnv("VIRTUAL_HOST")
virtualHost = "login.localhost:3000"
domainRegex = regexp.MustCompile(`^(?:https?://)?([-a-z0-9]+)(?:\.` + virtualHost + `)*$`)
}
func main() {
// host := req.host
host := "http://acme.login.localhost:3000"
if result := extractSubdomain(host); result != "" {
fmt.Printf("Subdomain detected: %s\n", result)
return
}
fmt.Println("No subdomain detected")
}
The url package has a function parse that allows you to parse an URL. The parsed URL instance has a method Hostname which will return you the hostname.
package main
import (
"fmt"
"log"
"net/url"
)
func main() {
u, err := url.Parse("http://login.localhost:3000")
if err != nil {
log.Fatal(err)
}
fmt.Println(u.Hostname())
}
Output:
login.localhost
See https://play.golang.com/p/3R1TPyk8qck
Update:
My previous answer only dealt with parsing the host name. Since then I have been using the following library to parse the domain suffix from the host name. Once you have that, it is simple to strip the domain and leave only the subdomain prefix.
https://pkg.go.dev/golang.org/x/net/publicsuffix
I have found that it can be a bit tricky to exactly identify the difference between subdomain and host, without a little help first from this package that can identify common suffixes. For instance, internally we may have a domain coming from a kubernetes ingress:
foo.bar.host.kube.domain.com.au
The host is "host" and the subdomain is "foo.bar". Even with the help of the publicsuffix library it won't know that "kube" is part of the internal domain components. So you have to add some more of your own hinting to match.
This is what I've used
func getSubdomain(r *http.Request) string {
//The Host that the user queried.
host := r.URL.Host
host = strings.TrimSpace(host)
//Figure out if a subdomain exists in the host given.
hostParts := strings.Split(host, ".")
fmt.Println("host parts",hostParts)
lengthOfHostParts := len(hostParts)
// scenarios
// A. site.com -> length : 2
// B. www.site.com -> length : 3
// C. www.hello.site.com -> length : 4
if lengthOfHostParts == 4 {
return strings.Join([]string{hostParts[1]},"") // scenario C
}
if lengthOfHostParts == 3 { // scenario B with a check
subdomain := strings.Join([]string{hostParts[0]},"")
if subdomain == "www" {
return ""
} else {
return subdomain
}
}
return "" // scenario A
}
I am having some trouble when using github.com/go-validator/validator to validate regex some phone numbers with this prefix +62, 62, 0, for instance number e.g. +628112blabla, 0822blablabla, 628796blablabla.
I have try my regex on online regex tester and no issue with the regex on that. Here the regex is :
(0|\+62|062|62)[0-9]+$
But when I try with my go implement with it, the regex not working. This is my code for implement the purpose :
type ParamRequest struct {
PhoneNumber string `validate:"nonzero,regexp=(0|\+62|062|62)[0-9]+$"`
ItemCode string `validate:"nonzero"`
CallbackUrl string `validate:"nonzero"`
}
func (c *TopupAlloperatorApiController) Post() {
var v models.TopupAlloperatorApi
interf := make(map[string]interface{})
json.Unmarshal(c.Ctx.Input.RequestBody, &interf)
logs.Debug(" Json Input Request ", interf)
var phone, item, callback string
if _, a := interf["PhoneNumber"].(string); a {
phone = interf["PhoneNumber"].(string)
}
if _, b := interf["ItemCode"].(string); b {
item = interf["ItemCode"].(string)
}
if _, c := interf["CallbackUrl"].(string); c {
callback = interf["CallbackUrl"].(string)
}
ve := ParamRequest{
PhoneNumber: phone,
ItemCode: item,
CallbackUrl: callback,
}
logs.Debug(" Param Request ", ve)
err := validator.Validate(ve)
if err == nil {
//success
}else{
// not success
}
Many thanks for anything help. Thank you.
Because you are using regexp to check PhoneNumber that won't be matching if the value is empty it is better to remove nonzero from the validation.
I have checked out documentation and haven't found examples where you can use both: nonzero and regexp.
Also you need to make your regex symbol-escaped, otherwise it won't be detected by reflection. It means you should use (0|\\+62|062|62)[0-9]+$ in your code. Here is example where problem is: symbol escaping in struct tags
And also, please try to use this regexp: ^\\+{0,1}0{0,1}62[0-9]+$
I would like to filter some file in directory.
For example I have directory "MyDir" with 2 files and 1 dir:
foo.doc
foo.mp3
file.txt
file.properties
dir
3.1 foodir.pk
3.2 foodir.txt
I need to define files in one expression:
not ".doc"
not ".mp3"
not "dir\".
No you cannot use regular expressions in Inno Setup.
But you do not need them for your task, just use plain wildcards:
[Files]
Source: "*.*"; Excludes: "*.doc, *.mp3, dir"; DestDir: "{app}"; Flags: recursesubdirs
See [Files] section in Inno Setup documentation.
Though you cannot use any kind of exclude mask/pattern in [UninstallDelete] and [InstallDelete] sections.
It's for a good reason. You should only delete files you explicitly choose to delete. Not delete all files, only choosing few files you do not want to delete.
Have a look at:
http://d.hatena.ne.jp/ir9Ex/20120322/1332397961
This particular implementation uses VB RegExp, searching for strings containing.
Update:
Yes and No, not directly
{=============================================================================}
{* Global and case insensitive search. }
{* Usage: <file>, <search>, <replace/return> }
function regExpFile( FileName, RE_Pattern, RE_Replace: ansiString ): string;
var
RegExp: variant;
CntIn, CntOut: longint;
TextRowInAll: tArrayOfString;
TextRowInNum: longint;
TextRowIn: ansiString;
TextRowOut: variant;
TextRowOutAll: ansiString; //* Container for the returned string.
begin
Result := ''; { No matches yet. }
TextRowOutAll := ''; { Default return string. }
CntOut := 0;
try
RegExp := createOleObject( 'VBScript.RegExp' );
except
raiseException('VBScript RegExp is required to complete the post-installation process.'#13#10#13#10'(Error: ' + GetExceptionMessage);
end;
RegExp.Pattern := RE_Pattern;
RegExp.Global := TRUE;
RegExp.IgnoreCase := TRUE;
if loadStringsFromFile( FileName, TextRowInAll ) then begin
TextRowInNum := getArrayLength( TextRowInAll );
for CntIn := 0 to (TextRowInNum - 1) do begin
TextRowIn := TextRowInAll[ CntIn ];
if RegExp.Test( TextRowIn ) then begin { match or nothing... }
TextRowOut := RegExp.Replace( TextRowIn, RE_Replace );
if not varIsClear( TextRowOut ) then begin { At least one match. }
if CntOut < 1 then begin
TextRowOutAll := TextRowOut;
end
else begin
TextRowOutAll := TextRowOutAll + #13#10 + TextRowOut;
end;
CntOut := CntOut + 1;
end;
end;
end;
end;
Result := TextRowOutAll;
end;
{ Ex. Search for and return the numbers only from the string: "...Version: 5.8..." }
{ RE_Pattern := '(.*version.*)([0-9]+\.[0-9]+)(.*)'; }
{ RE_Replace := '[$2]'; }
{ Deps: VBScript.RegExp }
{ 20160828 }
{ (Inspiration) Trackback - http://d.hatena.ne.jp/ir9Ex/20120322/1332397961 }
{ Microsoft Beefs Up VBScript with Regular Expressions - https://msdn.microsoft.com/en-us/library/ms974570.aspx }
{ ----------------------------------------------------------------------------- }