Commit 6721a499 authored by Rahul A. Sutar's avatar Rahul A. Sutar
Browse files

CoreOS Package commit

Committing CoreOS package.
Blank script file. The script file will have shell commands to install all the dependencies.
parent d38c29ce
Branches
Tags
2 merge requests!2Stagingbranch,!1Dev branch
Showing with 477 additions and 0 deletions
package coreos
import (
"sync"
"GolangFullStack/server/api/server/config"
"github.com/gocraft/dbr"
)
// Hold a single global connection (pooling provided by sql driver)
var sqlConnection *dbr.Connection
var sqlOnce sync.Once
//GetSQLConnection to db
func GetSQLConnection() (*dbr.Connection, error) {
sqlOnce.Do(func() {
// create a connection db(e.g. "postgres", "mysql", or "sqlite3")
connection, _ := dbr.Open("mysql", config.MysqlDSN, nil)
// connection.SetMaxIdleConns(10)
// connection.SetMaxOpenConns(5)
sqlConnection = connection
})
return sqlConnection, nil
}
package coreos
import (
"GolangFullStack/server/api/server/config"
"fmt"
"sync"
mgo "gopkg.in/mgo.v2"
)
var instance *mgo.Session
var once sync.Once
//GetMongoConnection method
func GetMongoConnection() *mgo.Session {
once.Do(func() {
Host := []string{
config.MONGODSN,
}
const (
Username = ""
Password = ""
Database = config.DBNAME
)
session, err := mgo.DialWithInfo(&mgo.DialInfo{
Addrs: Host,
Username: Username,
Password: Password,
Database: Database,
})
if err != nil {
}
//defer session.Close()
fmt.Printf("Connected to replica set %v!\n", session.LiveServers())
instance = session
})
return instance
}
package coreos
import (
"GolangFullStack/server/api/server/config"
"github.com/garyburd/redigo/redis"
)
//GetWorkPool ss
func GetWorkPool() *redis.Pool {
var redisPool = &redis.Pool{
MaxActive: 5,
MaxIdle: 5,
Wait: true,
Dial: func() (redis.Conn, error) {
return redis.Dial("tcp", config.REDISDSN, redis.DialDatabase(3))
},
}
return redisPool
}
package coreos
import (
"sync"
"github.com/labstack/echo"
)
var echoInstance *echo.Echo
var echoOnce sync.Once
//GetEcho method
func GetEcho() *echo.Echo {
echoOnce.Do(func() {
e := echo.New()
echoInstance = e
})
return echoInstance
}
package coreos
import (
"GolangFullStack/server/api/server/config"
"fmt"
"time"
"github.com/allegro/bigcache"
)
var bigcacheConfig = bigcache.Config{
// number of shards (must be a power of 2)
// Shards: 4096,
Shards: config.BIGCACHEShards,
// time after which entry can be evicted
LifeWindow: config.BIGCACHELifeWindow * time.Hour,
// rps * lifeWindow, used only in initial memory allocation
MaxEntriesInWindow: 1000 * 10 * 60,
// MaxEntriesInWindow: 10,
// max entry size in bytes, used only in initial memory allocation
MaxEntrySize: config.BIGCACHEMaxEntrySize,
// prints information about additional memory allocation
Verbose: config.BIGCACHEVerbose,
// cache will not allocate more memory than this limit, value in MB
// if value is reached then the oldest entries can be overridden for the new ones
// 0 value means no size limit
HardMaxCacheSize: config.BIGCACHEHardMaxCacheSize,
// callback fired when the oldest entry is removed because of its
// expiration time or no space left for the new entry. Default value is nil which
// means no callback and it prevents from unwrapping the oldest entry.
OnRemove: nil,
}
var cache, initErr = bigcache.NewBigCache(bigcacheConfig)
//GetValue GetValue
func GetValue(key string) ([]byte, error) {
return cache.Get(key)
}
//SetValue SetValue
func SetValue(key string, value []byte) {
cache.Set(key, value)
}
//GetLength GetLength
func GetLength() int {
return cache.Len()
}
//Callback function executed when cache element is removed.
//Executed only when onRemove of cache config poting to this function
func onRemove(key string, entry []byte) {
fmt.Println(key + " removed at " + time.Now().String())
}
package coreos
import (
"fmt"
"github.com/spf13/viper"
)
//InitViper function to initialize viper
func InitViper() {
viper.SetConfigName("config") // name of config file (without extension)
viper.AddConfigPath(".") // optionally look for config in the working directory
err := viper.ReadInConfig()
// Find and read the config file
if err != nil { // Handle errors reading the config file
panic(fmt.Errorf("Fatal error config file %s ", err))
}
}
//GetConfig method to get configs from config file
func GetConfig(keyName string) string {
keyValue := viper.GetString(keyName)
return keyValue
}
package coreos
import (
"os"
"gopkg.in/mgo.v2"
)
type DB struct {
Session *mgo.Session
}
func (db *DB) DoDial() (s *mgo.Session, err error) {
return mgo.Dial(DBUrl())
}
func (db *DB) Name() string {
return "swapnilapp"
}
func DBUrl() string {
dburl := os.Getenv("MONGOHQ_URL")
if dburl == "" {
dburl = "localhost"
}
return dburl
}
package coreos
import (
"os"
"testing"
"github.com/stretchr/testify/assert"
)
var db DB = DB{}
func cleanEnv() {
os.Setenv("MONGOHQ_URL", "")
}
func TestGetDbUrl(t *testing.T) {
assert.Equal(t, "localhost", DBUrl())
os.Setenv("MONGOHQ_URL", "abc")
assert.Equal(t, "abc", DBUrl())
cleanEnv()
}
func TestDBName(t *testing.T) {
assert.Equal(t, "swapnilapp", db.Name())
}
func BenchmarkDoDial(b *testing.B) {
for i := 0; i < b.N; i++ {
db.DoDial()
}
}
package coreos
import (
"encoding/json"
"log"
"gopkg.in/mgo.v2/bson"
)
//ConvertToJSON converts []bson to json
// func ConvertToJSON(data []bson.M) string {
// respBody, err := json.MarshalIndent(data, "", "")
// if err != nil {
// log.Fatal(err)
// }
// return string(respBody)
// }
//ConvertToJSON converts []bson to json
func ConvertToJSON(data []bson.M) string {
respBody, err := json.MarshalIndent(data, "", "")
if err != nil {
log.Fatal(err)
}
return string(respBody)
}
package coreos
import (
"fmt"
"strings"
jwt "github.com/dgrijalva/jwt-go"
"github.com/labstack/echo/middleware"
)
const (
//JwtKey for key of EP
JwtKey = "MKCL-EP-1234567890"
)
// JwtCustomClaims are custom claims extending default ones.
type JwtCustomClaims struct {
Username string `json:"username"`
jwt.StandardClaims
}
// GetJwtConfig middleware with the custom claims type
func GetJwtConfig() middleware.JWTConfig {
jwtConfig := middleware.JWTConfig{
Claims: &JwtCustomClaims{},
SigningKey: []byte(JwtKey),
}
return jwtConfig
}
// DecodeToken decode token
func DecodeToken(tokenFromRequest string) jwt.MapClaims {
tokenFromRequest = strings.Trim(strings.Split(tokenFromRequest, "Bearer")[1], " ")
// get data i.e.Claims from token
token, _ := jwt.Parse(tokenFromRequest, func(token *jwt.Token) (interface{}, error) {
// Don't forget to validate the alg is what you expect:
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
return JwtKey, nil
})
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
return nil
}
return claims
}
package coreos
import (
"os"
"github.com/sirupsen/logrus"
)
var logger = logrus.New()
func init() {
//log.Formatter = new(logger.JSONFormatter)
logger.Formatter = new(logrus.TextFormatter) // default
logger.Level = logrus.ErrorLevel
file, err := os.OpenFile("GolangFullStack.log", os.O_CREATE|os.O_APPEND, 0666)
if err == nil {
logger.Out = file
} else {
logger.Info("Failed to log to file, using default stderr")
}
}
//Debug Debug
func Debug(message string) {
logger.Debug(message)
}
//Info Info
func Info(message string) {
logger.Info(message)
}
//Warn Warn
func Warn(message string) {
logger.Warn(message)
}
//Error Error
func Error(message string) {
logger.Error(message)
}
//Panic Panic
func Panic(message string) {
logger.Panic(message)
}
package coreos
import (
"GolangFullStack/server/api/server/config"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
)
type SMS struct {
MobileNumber string
Message string
UserName string
Password string
SenderID string
CDMAHeader string
}
// SendSMS : send SMS Service
func SendSMS(smsObject SMS) error {
var postURL string
postURL = config.SMSAPIURL + "?UserName=" + smsObject.UserName + "&password=" + smsObject.Password + "&MobileNo=" + smsObject.MobileNumber + "&SenderID=" + smsObject.SenderID + "&CDMAHeader=" + smsObject.CDMAHeader + "&Message=" + url.QueryEscape(smsObject.Message)
// fmt.Println(postURL)
resp, err := http.Get(postURL)
if err != nil {
// handle error
log.Fatal(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
fmt.Println(body)
return err
}
// GetSMSObject : get sms object
func GetSMSObject() SMS {
var smsObject = new(SMS)
smsObject.SenderID = "MKCLTD"
smsObject.UserName = "solar1_trans"
smsObject.Password = "trans123"
smsObject.CDMAHeader = "MKCLTD"
return *smsObject
}
package coreos
import (
"github.com/go-playground/locales/en"
"gopkg.in/go-playground/validator.v9"
ut "github.com/go-playground/universal-translator"
en_translations "gopkg.in/go-playground/validator.v9/translations/en"
)
//Validate method
func Validate(s interface{}) map[string]string {
var validate *validator.Validate
var uni *ut.UniversalTranslator
validate = validator.New()
en := en.New()
//mr := mr.New()
uni = ut.New(en, en)
trans, _ := uni.GetTranslator("en")
en_translations.RegisterDefaultTranslations(validate, trans)
// mr_translations.RegisterDefaultTranslations(validate, trans)
//For custom error message
// validate.RegisterTranslation("required", trans, func(ut ut.Translator) error {
// // fmt.Println(ut)
// return ut.Add("required", "{0} must have a value!", true) // see universal-translator for details
// }, func(ut ut.Translator, fe validator.FieldError) string {
// t, _ := ut.T("required", fe.Field())
// return t
// })
err := validate.Struct(s)
if err != nil {
errs := err.(validator.ValidationErrors)
//customErrs := map[string]string{}
customErrs := make(map[string]string, len(errs))
for _, e := range errs {
// can translate each error one at a time.
customErrs[e.Namespace()] = e.Translate(trans)
}
return customErrs
}
return nil
}
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment