Skip to content

Commit

Permalink
Merge pull request #83 from sooraj-sky/feature/env
Browse files Browse the repository at this point in the history
closes #74; added env package
  • Loading branch information
sooraj-sky authored Feb 26, 2023
2 parents abdbfb9 + 232a058 commit 2d067ad
Show file tree
Hide file tree
Showing 7 changed files with 124 additions and 47 deletions.
17 changes: 7 additions & 10 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,22 @@ import (
"gorm.io/driver/postgres"
"gorm.io/gorm"
"log"
"os"
dbops "sky-meter/packages/dbops"
skyenv "sky-meter/packages/env"
skymeter "sky-meter/packages/httpserver"
sentry "sky-meter/packages/logger"
yamlops "sky-meter/packages/yamlops"
)

func init() {
skyenv.InitEnv()
}

func main() {
log.Println("Launching sky-meter")
sentry.SentryInit()
dbconnect := os.Getenv("dbconnect")
opsgenieSecret := os.Getenv("opsgeniesecret")
if opsgenieSecret == "" {
log.Fatal("Please specify the opsgeniesecret as environment variable, e.g. export dbconnect=host=localhost user=postgres password=postgres dbname=postgres port=5433 sslmode=disable")
}

if opsgenieSecret == "" {
log.Fatal("Please specify the opsgeniesecret as environment variable, e.g. export opsgeniesecret=<your-value-here>")
}
allEnv := skyenv.GetEnv()
dbconnect := allEnv.DbUrl
db, err := gorm.Open(postgres.New(postgres.Config{
DSN: dbconnect,
PreferSimpleProtocol: true, // disables implicit prepared statement usage
Expand Down
13 changes: 13 additions & 0 deletions models/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,3 +127,16 @@ type AlertGroups struct {
Name string
Email string
}

type AllEnvs struct {
DnsServer string
Port string
EmailPass string
EmailFrom string
EmailPort string
EmailServer string
OpsgenieSecret string
SentryDsn string
Mode string
DbUrl string
}
29 changes: 10 additions & 19 deletions packages/alerts/alert.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ import (
"io/ioutil"
"log"
"net/http"
"os"
models "sky-meter/models"
skyenv "sky-meter/packages/env"

"github.com/opsgenie/opsgenie-go-sdk-v2/alert"
"github.com/opsgenie/opsgenie-go-sdk-v2/client"
Expand All @@ -18,12 +18,8 @@ import (

func SendMail(i models.SmtpErr) {

log.Println(i.Mailto, "mailto")

emailPass := os.Getenv("emailpass")
if emailPass == "" {
log.Fatal("Please specify the emailpass as environment variable, e.g. env emailpass=your-pass go run http-server.go")
}
allEnv := skyenv.GetEnv()
emailPass := allEnv.EmailPass

t := template.New("error.html")

Expand All @@ -38,18 +34,17 @@ func SendMail(i models.SmtpErr) {
log.Println(err)
}

log.Println("emails areee", i.Mailto)
for k := range i.Mailto {

result := tpl.String()
m := gomail.NewMessage()
m.SetHeader("From", os.Getenv("emailFrom"))
m.SetHeader("From", allEnv.EmailFrom)
m.SetHeader("To", i.Mailto[k])
m.SetHeader("Subject", i.Subject)
m.SetBody("text/html", result)
intPort, _ := strconv.Atoi(os.Getenv("EmailPort"))
intPort, _ := strconv.Atoi(allEnv.EmailPort)

d := gomail.NewDialer(os.Getenv("emailServer"), intPort, os.Getenv("emailFrom"), emailPass)
d := gomail.NewDialer(allEnv.EmailServer, intPort, allEnv.EmailFrom, emailPass)

if err := d.DialAndSend(m); err != nil {
log.Println(err)
Expand All @@ -65,10 +60,8 @@ type error interface {

func OpsgenieCreateAlert(errorurl string, description error, group string) string {
downMessege := "Alert Endpint " + errorurl + " is Down"
opsgenieSecret := os.Getenv("opsgeniesecret")
if opsgenieSecret == "" {
log.Fatal("Please specify the opsgeniesecret as environment variable, e.g. export opsgeniesecret=")
}
allEnv := skyenv.GetEnv()
opsgenieSecret := allEnv.OpsgenieSecret

alertClient, err := alert.NewClient(&client.Config{
ApiKey: opsgenieSecret,
Expand All @@ -95,11 +88,9 @@ func OpsgenieCreateAlert(errorurl string, description error, group string) strin
func CheckAlertStatus(alertRequestId string) string {
apiclient := &http.Client{}
url := "https://api.opsgenie.com/v2/alerts/requests/" + alertRequestId + "?identifierType=id"
opsgenieSecret := os.Getenv("opsgeniesecret")
allEnv := skyenv.GetEnv()
opsgenieSecret := allEnv.OpsgenieSecret
opsgenieSecretString := "GenieKey " + opsgenieSecret
if opsgenieSecret == "" {
log.Fatal("Please specify the opsgeniesecret as environment variable, e.g. export opsgeniesecret=")
}

req, err := http.NewRequest("GET", url, nil)
if err != nil {
Expand Down
80 changes: 80 additions & 0 deletions packages/env/envexport.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package env

import (
"encoding/json"
"log"
"os"
"reflect"
models "sky-meter/models"
)

// To add a new env variable, add that variable to models.AllEnvs struct.

// This function is used to get the keys of a struct type. It does this by creating a pointer to an instance of the models.AllEnvs struct type, using reflection to get the type of this instance, and then checking that the type is a struct.
// If it is a struct, it iterates through all of the fields of the struct and appends their names to a slice of strings, which it returns at the end.
func GetEnvStructKeys() (envKeys []string) {
a := &models.AllEnvs{}
t := reflect.TypeOf(*a)
if t.Kind() == reflect.Struct {
for i := 0; i < t.NumField(); i++ {
envKeys = append(envKeys, t.Field(i).Name)

}
}
return envKeys
}

// This function is used to initialize the environment variables needed by the program.
// It does this by calling the GetEnvStructKeys function to get a slice of the keys of the models.AllEnvs struct, and then iterating through this slice.
// For each key, it retrieves the corresponding environment variable using the os.Getenv function, and checks that it is not an empty string.
// If the environment variable is empty, it logs an error message indicating that the variable needs to be specified and terminates the program.

func InitEnv() {

envNames := GetEnvStructKeys()

var envStatus []string

for i := range envNames {
envValue := os.Getenv(envNames[i])
if envValue == "" {
envStatus = append(envStatus, "\n Variable "+envNames[i]+" is not set \n")
}
}
if envStatus != nil {

log.Fatal(envStatus)

}

}

// This function is used to retrieve and return the environment variables needed by the program as an instance of the models.AllEnvs struct.
// It does this by calling the GetEnvStructKeys function to get a slice of the keys of the models.AllEnvs struct, creating an empty map[string]string and then iterating through the slice of keys.
// For each key, it retrieves the corresponding environment variable using the os.Getenv function and stores it in the map using the key as the map key.
// Next, it marshals the map into a JSON string using the json.Marshal function.
// It then unmarshals the JSON string into an instance of the models.AllEnvs struct using the json.Unmarshal function, and returns this instance.
// If either the json.Marshal or json.Unmarshal functions return an error, it logs the error.

func GetEnv() (outputEnv models.AllEnvs) {
envNames := GetEnvStructKeys()

var Envvalues models.AllEnvs
mapOfEnv := make(map[string]string)

for i := range envNames {
mapOfEnv[envNames[i]] = os.Getenv(envNames[i])
}

jsonStr, err := json.Marshal(mapOfEnv)

if err != nil {
log.Println(err)
}

if err := json.Unmarshal(jsonStr, &Envvalues); err != nil {
log.Println(err)
}

return Envvalues
}
5 changes: 3 additions & 2 deletions packages/httpres/trace.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@ import (
"log"
"net/http"
"net/http/httptrace"
"os"
"time"

models "sky-meter/models"
skydns "sky-meter/packages/dns"
skyenv "sky-meter/packages/env"
)

func GetHttpdata(url string, timeout time.Duration, SkipSsl bool) (httpdata []byte, httpstatuscode int, errs error) {
Expand Down Expand Up @@ -57,8 +57,9 @@ func tlsConfig() *tls.Config {
}

func trace() (*httptrace.ClientTrace, *models.Debug) {
allEnv := skyenv.GetEnv()
//DNS settings
dnsServer := os.Getenv("dnsserver") // Replace with your desired DNS server IP address
dnsServer := allEnv.DnsServer
resolver := skydns.CustomResolver(dnsServer)
fmt.Sprintln(resolver)
d := &models.Debug{}
Expand Down
9 changes: 3 additions & 6 deletions packages/httpserver/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,15 @@ package htttpserver
import (
"log"
"net/http"
"os"

"github.com/gorilla/mux"
api "sky-meter/packages/api"
skyenv "sky-meter/packages/env"
)

func InitServer() {
port := os.Getenv("PORT")
if port == "" {
log.Fatal("Please specify the HTTP port as environment variable, e.g. env PORT=8081 go run http-server.go")
}

allEnv := skyenv.GetEnv()
port := allEnv.Port
log.Println("listening on port", port)
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/", api.HomeLink)
Expand Down
18 changes: 8 additions & 10 deletions packages/logger/sentry.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,25 @@ package sentry

import (
"log"
"os"

"github.com/getsentry/sentry-go"
skyenv "sky-meter/packages/env"
)

func SentryInit() {
mode := os.Getenv("mode")
allEnv := skyenv.GetEnv()
mode := allEnv.Mode
if mode == "dev" {
sentenv := os.Getenv("sentry_dsn")
if sentenv == "" {
log.Fatal("Please specify the sentry_dsn as environment variable, e.g. env sentry_dsn=https://your-dentry-dsn.com go run cmd/main.go")
}
senterr := sentry.Init(sentry.ClientOptions{
Dsn: sentenv,
sentryEnv := allEnv.SentryDsn
sentryerr := sentry.Init(sentry.ClientOptions{
Dsn: sentryEnv,
// Set TracesSampleRate to 1.0 to capture 100%
// of transactions for performance monitoring.
// We recommend adjusting this value in production,
TracesSampleRate: 1.0,
})
if senterr != nil {
log.Fatalf("sentry.Init: %s", senterr)
if sentryerr != nil {
log.Fatalf("sentry.Init: %s", sentryerr)
}

}
Expand Down

0 comments on commit 2d067ad

Please sign in to comment.