I am trying to create security group using goamz.
Below is my code.
package main
import (
"fmt"
"os"
"github.com/mitchellh/goamz/aws"
"github.com/mitchellh/goamz/ec2"
)
type SecurityGroup struct {
Id string `xml:"groupId"`
Name string `xml:"groupName"`
Description string `xml:"groupDescription"`
VpcId string `xml:"vpcId"`
}
func main() {
auth := aws.Auth{
AccessKey: os.Getenv("key"),
SecretKey: os.Getenv("secret"),
}
region := aws.Region{
Name : "us-east-1",
}
ec2conn := ec2.New(auth, region)
fmt.Printf("%+v\n", ec2conn)
resp, err := ec2conn.CreateSecurityGroup(ec2.SecurityGroup{Name: "testing12",
Description: "testing123", VpcId: "vpc-123456"})
fmt.Printf("%+v\n", resp)
if err != nil {
fmt.Printf("%s\n", err.Error())
}
}
And I get the below Response upon execution.
<nil>
Get /? XXXXXXXXX
unsupported protocol scheme ""
I am not sure whether we use any protocol explicitly to create.
Please help me understanding this.
Related
I am failing to create an Access Token for the Twillio Video Product with the golang SDK
In the docs there is golang sadly not mentioned
Does anyone of you know how I can create the required access token?
The JWT package mentioned in the examples of the other languages can not be found in the Go SDK.
I found that it is just not possible to do it with the default go SDK. I did follow the instructions on https://www.twilio.com/docs/iam/access-tokens and build the JWT myself. Maybe someone will find the solution handy:
package main
import (
"encoding/json"
"fmt"
"github.com/dvsekhvalnov/jose2go"
"log"
"time"
)
func main() {
accountSid := "XXX"
keySid := "YYY"
keySecret := "ZZZ"
username := "Simon"
roomName := "SimonsRoom"
now := time.Now()
type JWTPayload struct {
Jti string `json:"jti"`
Issuer string `json:"iss"`
Subject string `json:"sub"`
CreationUnixTimestamp int64 `json:"iat"`
NotBeforeUnixTimestamp int64 `json:"nbf"`
ExpiresUnixTimestamp int64 `json:"exp"`
Grants struct {
Identity string `json:"identity"`
Video struct {
Room string `json:"room"`
} `json:"video"`
} `json:"grants"`
}
payload := JWTPayload{
Jti: fmt.Sprintf("%s-%d",keySid,now.UnixNano()),
Issuer: keySid,
Subject: accountSid,
CreationUnixTimestamp: now.Unix(),
NotBeforeUnixTimestamp: now.Unix(),
ExpiresUnixTimestamp: now.Add(23*time.Hour).Unix(),
Grants: struct {
Identity string `json:"identity"`
Video struct {
Room string `json:"room"`
} `json:"video"`
}{
Identity: username,
Video: struct {
Room string `json:"room"`
}{
Room: roomName,
},
},
}
payloadByte, err := json.Marshal(payload)
if err != nil {
log.Fatal(err)
}
token, err := jose.SignBytes(payloadByte, jose.HS256, []byte(keySecret),
jose.Header("cty", "twilio-fpa;v=1"),
jose.Header("typ", "JWT"),
jose.Header("alg", "HS256"),
)
if err != nil {
log.Fatal(err)
}
fmt.Println(token)
}
I have a go client initialized to connect to a vCenter as follows. I am trying to get the version of the vCenter using the client. I did not find a very good source for this.
Which arguments to use inside retrieve() API to get the version and other information related to vCenter cluster?
import (
"context"
"fmt"
"net/url"
"github.com/vmware/govmomi"
)
func main() {
vURL := url.URL{
Scheme: "https",
Host: "10.30.8.34",
Path: "sdk",
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
client, err := govmomi.NewClient(ctx, vURL, true)
if err != nil {
fmt.Printf("Logging in error: %s\n", err.Error())
return
}
fmt.Println("Log in successful")
client.Logout(ctx)
}
Are you looking for VsanHostConfigInfoEx?
type VsanHostConfigInfoEx struct {
types.VsanHostConfigInfo
EncryptionInfo *VsanHostEncryptionInfo `xml:"encryptionInfo,omitempty"`
DataEfficiencyInfo *VsanDataEfficiencyConfig `xml:"dataEfficiencyInfo,omitempty"`
ResyncIopsLimitInfo *ResyncIopsInfo `xml:"resyncIopsLimitInfo,omitempty"`
ExtendedConfig *VsanExtendedConfig `xml:"extendedConfig,omitempty"`
DatastoreInfo BaseVsanDatastoreConfig `xml:"datastoreInfo,omitempty,typeattr"`
UnmapConfig *VsanUnmapConfig `xml:"unmapConfig,omitempty"`
WitnessHostConfig []VsanWitnessHostConfig `xml:"witnessHostConfig,omitempty"`
InternalExtendedConfig *VsanInternalExtendedConfig `xml:"internalExtendedConfig,omitempty"`
MetricsConfig *VsanMetricsConfig `xml:"metricsConfig,omitempty"`
UnicastConfig *VsanHostServerClusterUnicastConfig `xml:"unicastConfig,omitempty"`
DataInTransitEncryptionInfo *VsanInTransitEncryptionInfo `xml:"dataInTransitEncryptionInfo,omitempty"`
}
which implements VsanHostConfigInfo
type VsanHostConfigInfo struct {
DynamicData
Enabled *bool `xml:"enabled"`
HostSystem *ManagedObjectReference `xml:"hostSystem,omitempty"`
ClusterInfo *VsanHostConfigInfoClusterInfo `xml:"clusterInfo,omitempty"`
StorageInfo *VsanHostConfigInfoStorageInfo `xml:"storageInfo,omitempty"`
NetworkInfo *VsanHostConfigInfoNetworkInfo `xml:"networkInfo,omitempty"`
FaultDomainInfo *VsanHostFaultDomainInfo `xml:"faultDomainInfo,omitempty"`
}
So I currently have a function that will take in a string APIKey to check it against my Mongo collection. If nothing is found (not authenticated), it returns false - if a user is found, it returns true. My problem, however, is I'm unsure how to integrate this with a Martini POST route. Here is my code:
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/go-martini/martini"
_ "github.com/joho/godotenv/autoload"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type User struct {
Name string
APIKey string
}
func validateAPIKey(users *mongo.Collection, APIKey string) bool {
var user User
filter := bson.D{{"APIKey", APIKey}}
if err := users.FindOne(context.TODO(), filter).Decode(&user); err != nil {
fmt.Printf("Found 0 results for API Key: %s\n", APIKey)
return false
}
fmt.Printf("Found: %s\n", user.Name)
return true
}
func uploadHandler() {
}
func main() {
mongoURI := os.Getenv("MONGO_URI")
mongoOptions := options.Client().ApplyURI(mongoURI)
client, _ := mongo.Connect(context.TODO(), mongoOptions)
defer client.Disconnect(context.TODO())
if err := client.Ping(context.TODO(), nil); err != nil {
log.Fatal(err, "Unable to access MongoDB server, exiting...")
}
// users := client.Database("sharex_api").Collection("authorized_users") // commented out when testing to ignore unused warnings
m := martini.Classic()
m.Post("/api/v1/upload", uploadHandler)
m.RunOnAddr(":8085")
}
The validateAPIKey function works exactly as intended if tested alone, I am just unsure how I would run this function for a specific endpoint (in this case, /api/v1/upload).
I'm getting time to learn Go, and I'm having a problem dealing with yaml file.
this is my yaml file
---
endpoints:
service1:
url: "https://service1.com"
frequency: 2
interval: 1
service2:
url: "https://service2.com"
frequency: 3
interval: 2
My go code
package main
import (
"fmt"
"io/ioutil"
"reflect"
"gopkg.in/yaml.v3"
)
// Config define estrutura do arquivo de configuraĆ§Ć£o
type Config struct {
Endpoint map[string]interface{} `yaml:"endpoints"`
}
func main() {
yamlFile, err := ioutil.ReadFile("config.yml")
if err != nil {
fmt.Printf("Error reading YAML file: %s\n", err)
return
}
var yamlConfig Config
err = yaml.Unmarshal(yamlFile, &yamlConfig)
if err != nil {
fmt.Printf("Error parsing YAML file: %s\n", err)
}
for k := range yamlConfig.Endpoint {
nm := reflect.ValueOf(yamlConfig.Endpoint[k])
for _, key := range nm.MapKeys() {
strct := nm.MapIndex(key)
fmt.Println(key.Interface(), strct.Interface())
}
}
}
// PingEndpoint acessa os endpoint informados
func PingEndpoint(url string, frequency, interval int) {
// do something
}
Is there a better way to define the Config structure without using interface? And is really necessary use reflect do get properties of a service1 or exist a better whey to do that?
In general, an interface{} is used in this situation if you don't know the structure. In this case, the structure appears to be fixed:
type Service struct {
URL string `yaml:"url"`
Frequency int `yaml:"frequency"`
Interval int `yaml:"interval"`
}
type Config struct {
Endpoint map[string]Service `yaml:"endpoints"`
}
For your second question, you no longer need to deal with unknown fields after you do this, but even if you had interface{}, you can use type assertions (type yaml library unmarshals yaml into a map[interface{}]interface{}):
for k := range yamlConfig.Endpoint {
if mp, ok:=yamlConfig.Endpoint[k].(map[interface{}]interface{}); ok {
for key, value:=range mp {
}
}
}
I'm already posting a file and some params, but now I need to send nested params with a struct and I don't know where to use that (I'm new in Go).
This is what I have: https://play.golang.org/p/L4qx6AZhUO
Now, I'm creating this structs:
type S3 struct {
Accesskeyid string
Secretaccesskey string
Bucket string
}
type Test struct {
Outputformat string
Wait string
Output S3
File []byte
}
And I would like to send the Test struct WITH the file. Any ideas?
Thanks!
Okay, So given what you've told me and what little information I have with your example, I might do something like this.
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)
type S3 struct {
Accesskeyid string
Secretaccesskey string
Bucket string
}
type Test struct {
Outputformat string
Wait string
Output S3
File []byte
}
func main() {
myStrut := Test{
Outputformat: "Json",
Wait: "Some Time",
Output: S3{
Accesskeyid: "my id",
Secretaccesskey: "secret id",
Bucket: "east",
},
File: []byte(`some bytes`),
}
jsonValue, err := json.Marshal(myStrut)
if err != nil {
panic(err)
}
fmt.Printf("Test showing that data was marshalled\n %q\n", jsonValue)
resp, err := http.Post("some url", "application/json", bytes.NewBuffer(jsonValue))
if err != nil {
panic(err)
}
fmt.Println(resp.Status)
}
Now from what i gleamed in the comments you might be also having trouble opening the file as a byte array to assign to your struct. Here's an example you can use you help you open the file as a byte array so that you can assign those bytes to your struct.
package main
import (
"fmt"
"io/ioutil"
)
func main() {
//An example of how to open a file and turn it into bytes for your struct
byteArray, err := ioutil.ReadFile("input.txt")
if err != nil {
panic(err)
}
fmt.Println(byteArray)
}