package main
import (
"bufio"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strconv"
"strings"
sdk "github.com/aziontech/azionapi-go-sdk/edgefirewall"
)
type Response struct {
Results struct {
Name string `json:"name"`
ID int `json:"id"`
} `json:"results"`
}
// Define the firewall URL as a constant
const (
firewallURL = "https://api.azionapi.net/"
)
// Client struct to hold the API client
type Client struct {
apiClient sdk.APIClient
}
func main() {
// Request the user's personal token
fmt.Println("Hey, there! Welcome to Edge Firewall example")
fmt.Println("Please, provide your Personal Token: ")
var personalToken string
fmt.Scanf("%s", &personalToken)
// Handle the firewall with the provided token
err := firewallHandler(personalToken)
if err != nil {
fmt.Println(err)
}
}
// firewallHandler handles the firewall operations
func firewallHandler(personalToken string) error {
// Request the firewall name from the user
fmt.Println("Please, provide the Edge Firewall name: ")
reader := bufio.NewReader(os.Stdin)
firewallName, err := reader.ReadString('\n')
if err != nil {
return err
}
// Remove newline character from the firewall name
firewallName = strings.Replace(firewallName, "\n", "", -1)
// Create a new client and firewall
var httpClient *http.Client
client := NewClient(httpClient, firewallURL, personalToken)
err = client.NewFirewall(&firewallName)
if err != nil {
fmt.Println(err)
return err
}
return nil
}
// NewFirewall creates a new firewall
func (c *Client) NewFirewall(firewallName *string) error {
// Create a new context
ctx := context.Background()
// Create a new firewall request
firewall := new(sdk.CreateEdgeFirewallRequest)
firewall.Name = firewallName
fmt.Println("\nCreating Edge Firewall....\n")
// Execute the firewall request
req := c.apiClient.DefaultAPI.EdgeFirewallPost(ctx).CreateEdgeFirewallRequest(*firewall)
_, httpResp, err := req.Execute()
if err != nil {
fmt.Println(httpResp)
return err
}
// Read and print the response
bytes, err := io.ReadAll(httpResp.Body)
if err != nil {
return err
}
var response Response
err = json.Unmarshal(bytes, &response)
if err != nil {
fmt.Println(httpResp)
return err
}
fmt.Println("Edge Firewall succesfully created\n")
fmt.Println("Name: " + response.Results.Name)
fmt.Println("ID: " + strconv.Itoa(response.Results.ID) + "\n")
return nil
}
// NewClient creates a new client with the provided HTTP client, URL, and token
func NewClient(httpClient *http.Client, url string, token string) *Client {
// Create a new configuration
conf := sdk.NewConfiguration()
// Set the HTTP client and headers
conf.HTTPClient = httpClient
conf.AddDefaultHeader("Authorization", "token "+token)
conf.AddDefaultHeader("Accept", "application/json;version=3")
conf.Servers = sdk.ServerConfigurations{
{URL: url},
}
// Return a new client with the configuration
return &Client{
apiClient: *sdk.NewAPIClient(conf),
}
}