wafredir/main.go

80 lines
2.8 KiB
Go
Raw Normal View History

2020-05-30 02:03:03 +00:00
package main
import (
"encoding/csv"
"flag"
"io"
"log"
"os"
"strconv"
"strings"
)
var (
maxConcurrentRequests *int // the maximum number of allowed in flight HTTP requests. Only used with testing mode.
)
// Redirect is an instance of a single row in the csv file. It contains a value from each of the columns of the input csv file
type Redirect struct {
sourceURL string // the source URL we are redirecting from
destinationURL string // the target URL we are redirecting to
statusCode int // 301 or 302
}
func main() {
// Parse flags and determine actions
action := flag.String("action", "config", "action can be either 'config' or 'test'. 'config' will read the input csv file and generate FortiOS compliant configuration to create redirection policies. 'test' will read the input csv file and validate that the redirects are actually working by making requests at the source URL and validating a redirect to the destination URL actually occurs.")
csvFilePath := flag.String("csvfile", "redirects.csv", "path to an input csv file. The first column of the file should be the source URL, the second column of the file should be the destination URL, and the third column should be the status code (for example 301 or 302).")
maxConcurrentRequests = flag.Int("concurrentReq", 8, "only used with the action 'test'. Determines the maximum number concurrent HTTP GET requests which can be in flight at any given time.")
flag.Parse()
// Open and parse the CSV file and set up decoding
csvFile, err := os.Open(*csvFilePath)
if err != nil {
log.Fatalf("failed to open input csvFile '%s': %v", *csvFilePath, err)
}
rows := csv.NewReader(csvFile)
// Loop through each row until we reach the end and populate a slice of type Redirect
var redirects []Redirect
for {
row, err := rows.Read()
if err == io.EOF {
break // We've hit the end of the file
}
if err != nil {
log.Printf("failed to read row in CSV file: %v", err)
}
// Create a new instance of type Redirect and populate with data from CSV file
redirect := Redirect{sourceURL: strings.TrimSpace(row[0]), destinationURL: strings.TrimSpace(row[1])}
2020-05-30 02:03:03 +00:00
redirect.statusCode, err = strconv.Atoi(strings.TrimSpace(row[2]))
if err != nil {
log.Printf("skipping row: failed to convert status code '%s' to integer: %v", row[2], err)
continue
}
// Append the new redirect to the list of all redirects
redirects = append(redirects, redirect)
}
// Determine the next steps
if *action == "config" {
err := config(redirects)
if err != nil {
log.Fatalf("failed to build configuration: %v", err)
}
} else if *action == "test" {
err := test(redirects)
if err != nil {
log.Fatalf("failed to test redirects: %v", err)
}
} else {
log.Fatalf("invalid action %s specified", *action)
}
}