Skip to content

Commit

Permalink
First cut
Browse files Browse the repository at this point in the history
  • Loading branch information
gunjanap committed Jun 12, 2021
0 parents commit 4cfc5c9
Show file tree
Hide file tree
Showing 29 changed files with 2,437 additions and 0 deletions.
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2019 islax

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# microapp
Simple microservice framework in go!
145 changes: 145 additions & 0 deletions app.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
package microapp

import (
"context"
"database/sql"
"fmt"
"net/http"

"time"

migrate "github.com/golang-migrate/migrate/v4"
"github.com/golang-migrate/migrate/v4/database/mysql"
"github.com/golang-migrate/migrate/v4/source/file"
"github.com/gorilla/mux"
"github.com/islax/microapp/config"
"github.com/islax/microapp/event"
"github.com/islax/microapp/repository"
"github.com/jinzhu/gorm"
log "github.com/sirupsen/logrus"
)

// RouteSpecifier should be implemented by the class that sets routes for the API endpoints
type RouteSpecifier interface {
RegisterRoutes(router *mux.Router)
}

// App structure for tenant microservice
type App struct {
Name string
Config *config.Config
DB *gorm.DB
Router *mux.Router
server *http.Server
log *log.Logger
eventDispatcher event.EventDispatcher
}

// New creates a new microApp
func New(appName string, appConfigOverride map[string]string, appLog *log.Logger, appDB *gorm.DB, appEventDispatcher event.EventDispatcher) *App {
appConfig := config.NewConfig(appConfigOverride)
return &App{Name: appName, Config: appConfig, log: appLog, DB: appDB, eventDispatcher: appEventDispatcher}
}

// NewUnitOfWork creates new UnitOfWork
func (app *App) NewUnitOfWork(readOnly bool) *repository.UnitOfWork {
return repository.NewUnitOfWork(app.DB, readOnly)
}

//Initialize initializes properties of the app
func (app *App) Initialize(routeSpecifiers []RouteSpecifier) {
fmt.Println("--------- LOCAL MICROAPP -------------")
app.Router = mux.NewRouter()
app.Router.Use(mux.CORSMethodMiddleware(app.Router))
app.Router.Use(app.loggingMiddleware)

for _, routeSpecifier := range routeSpecifiers {
routeSpecifier.RegisterRoutes(app.Router)
}

app.server = &http.Server{
Addr: "0.0.0.0:80",
WriteTimeout: time.Second * 15,
ReadTimeout: time.Second * 15,
IdleTimeout: time.Second * 60,
Handler: app.Router,
}
}

//Start http server and start listening to the requests
func (app *App) Start() {
if err := app.server.ListenAndServe(); err != nil {
log.Println(err)
} else {
log.Println("Server started")
}
}

// Logger returns logger for specified module
func (app *App) Logger(module string) *log.Entry {
return app.log.WithFields(
log.Fields{
"service": app.Name,
"module": module,
})
}

// MigrateDB Looks for migrations directory and runs the migrations scripts in that directory
func (app *App) MigrateDB(connectionString string) {
logger := app.log

logger.Info("============ DB Migration Begin ============")
fsrc, err := (&file.File{}).Open("file://migrations")
if err != nil {
logger.Info("No migrations directory found. Skipping migrations. Error: ", err)
logger.Info("============ DB Migration End ============")
return
}
migrateDB, err := sql.Open("mysql", connectionString)
if err != nil {
logger.Fatal("Unable to open DB connection for migration: ", err)
}
migrateDBDriver, err := mysql.WithInstance(migrateDB, &mysql.Config{})
if err != nil {
logger.Error("Unable to prepare DB instance for migration: ", err)
}
m, err := migrate.NewWithInstance("file", fsrc, "mysql", migrateDBDriver)
if err != nil {
logger.Error("Unable to initialize DB instance for migration: ", err)
}
err = m.Up()
if err != nil {
if err.Error() == "no change" {
logger.Info("DB already in latest state.")
} else {
logger.Error("Failed to migrate DB: ", err)
// panic(err)
}
} else {
logger.Info("Successfully upgraded DB")
}
logger.Info("============ DB Migration End ============")
}

// Stop http server
func (app *App) Stop() {
wait, _ := time.ParseDuration("2m")
ctx, cancel := context.WithTimeout(context.Background(), wait)
defer cancel()

app.server.Shutdown(ctx)
}

func (app *App) loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
app.Logger("HTTP").Println(r.RequestURI)
next.ServeHTTP(w, r)
})
}

// DispatchEvent delegates to eventDispatcher.
func (app *App) DispatchEvent(token string, topic string, payload interface{}) {
if app.eventDispatcher != nil {
app.eventDispatcher.DispatchEvent(token, topic, payload)
}
}
134 changes: 134 additions & 0 deletions clients/APIClient.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
package clients

import (
"bytes"
"encoding/json"
"errors"
"io"
"io/ioutil"
"net/http"
"strconv"
"strings"

microLog "github.com/islax/microapp/log"
)

// APIClient represents the actual client calling microservice
type APIClient struct {
BaseURL string
HTTPClient *http.Client
}

func (apiClient *APIClient) doRequest(url string, requestMethod string, rawToken string, payload map[string]interface{}) (interface{}, error) {
var body io.Reader
if payload != nil {
bytePayload, err := json.Marshal(payload)
stringPayload := string(bytePayload)
microLog.Logger.Info(stringPayload)

if err != nil {
return nil, err
}
body = bytes.NewBuffer(bytePayload)
}

request, err := http.NewRequest(requestMethod, apiClient.BaseURL+url, body)
if err != nil {
return nil, err
}

if rawToken != "" {
if strings.HasPrefix(rawToken, "Bearer") {
request.Header.Add("Authorization", rawToken)
} else {
request.Header.Add("Authorization", "Bearer "+rawToken)
}
}
request.Header.Set("Content-Type", "application/json")

if err != nil {
microLog.Logger.Error(err)
return nil, err
}

response, err := apiClient.HTTPClient.Do(request)
if err != nil {
microLog.Logger.Error(err)
return nil, err
}

defer response.Body.Close()
if response.StatusCode > 300 { // All 3xx, 4xx, 5xx are considered errors
errorBytes, _ := ioutil.ReadAll(response.Body)
errorString := string(errorBytes)
microLog.Logger.Error(errorString)
return nil, errors.New("Received Status Code " + strconv.Itoa(response.StatusCode))
}

var mapResponse interface{}
err = json.NewDecoder(response.Body).Decode(&mapResponse)
if err != nil {
return nil, err
}

return mapResponse, nil
}

// DoGet is a generic method to carry out RESTful calls to the other external microservices in ISLA
func (apiClient *APIClient) DoGet(requestString string, rawToken string) (map[string]interface{}, error) {
response, err := apiClient.doRequest(requestString, http.MethodGet, rawToken, nil)
if err != nil {
return nil, err
}

mapResponse, ok := response.(map[string]interface{})
if !ok {
return nil, errors.New("Could not parse Json to map")
}
return mapResponse, nil
}

// DoGetList is a generic method to carry out RESTful calls to the other external microservices in ISLA
func (apiClient *APIClient) DoGetList(requestString string, rawToken string) ([]map[string]interface{}, error) {
response, err := apiClient.doRequest(requestString, http.MethodGet, rawToken, nil)
if err != nil {
return nil, err
}
sliceOfGenericObjects, ok := response.([]interface{})
if !ok {
return nil, errors.New("Could not parse Json to map")
}
var sliceOfMapObjects []map[string]interface{}
for _, obj := range sliceOfGenericObjects {
mapObject, ok := obj.(map[string]interface{})
if ok {
sliceOfMapObjects = append(sliceOfMapObjects, mapObject)
} else {
return nil, errors.New("Could not parse Json to map")
}
}
return sliceOfMapObjects, nil
}

// DoPost is a generic method to carry out RESTful calls to the other external microservices in ISLA
func (apiClient *APIClient) DoPost(requestString string, rawToken string, payload map[string]interface{}) (map[string]interface{}, error) {
response, err := apiClient.doRequest(requestString, http.MethodPost, rawToken, payload)
if err != nil {
return nil, err
}

mapResponse, ok := response.(map[string]interface{})
if !ok {
return nil, errors.New("Could not parse Json to map")
}
return mapResponse, nil
}

// DoDelete is a generic method to carry out RESTful calls to the other external microservices in ISLA
func (apiClient *APIClient) DoDelete(requestString string, rawToken string, payload map[string]interface{}) error {
_, err := apiClient.doRequest(requestString, http.MethodDelete, rawToken, payload)
if err != nil {
return err
}
return nil
}
62 changes: 62 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package config

import (
"fmt"

"github.com/spf13/viper"
)

// Config sdk for getting key values from settings file
type Config struct {
viper *viper.Viper
}

// NewConfig initializes configuration from settings file
func NewConfig(defaults map[string]string) *Config {
config := &Config{viper: viper.New()}

config.viper.SetDefault("ISLA_JWT_SECRET", "Secret key for test")

config.viper.SetEnvPrefix("ISLA_")
config.viper.AutomaticEnv()

config.viper.SetConfigName("settings")
config.viper.AddConfigPath(".")

err := config.viper.ReadInConfig()
if err != nil {
panic(fmt.Errorf("Can not load config file: %s", err))
}

return config
}

//IsSet checks if a key passed as a parameter has been set a value
func (config *Config) IsSet(key string) bool {
return config.viper.IsSet(key)
}

//GetBool returns boolean value set for a key passed to this function
func (config *Config) GetBool(key string) bool {
return config.viper.GetBool(key)
}

//GetString return string value set for a key passed to this function
func (config *Config) GetString(key string) string {
return config.viper.GetString(key)
}

//GetInt return int value set for a key passed to this function
func (config *Config) GetInt(key string) int {
return config.viper.GetInt(key)
}

//GetMapString returns the value associated with the key as a map of strings
func (config *Config) GetMapString(key string) map[string]string {
return config.viper.GetStringMapString(key)
}

//GetMap returns the value associated with the key as a map of interfaces
func (config *Config) GetMap(key string) map[string]interface{} {
return config.viper.GetStringMap(key)
}
25 changes: 25 additions & 0 deletions controllers/HealthController.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package controllers

import (
"net/http"

"github.com/gorilla/mux"
)

// HealthController provides method to check health and readiness
type HealthController struct {
}

// NewHealthController returns a new instance of HealthController
func NewHealthController() *HealthController {
return &HealthController{}
}

// RegisterRoutes implements interface RouteSpecifier
func (controller *HealthController) RegisterRoutes(router *mux.Router) {
healthRouter := router.PathPrefix("/health").Subrouter()
healthRouter.HandleFunc("", controller.healthCheck).Methods("GET")
}

func (controller *HealthController) healthCheck(w http.ResponseWriter, r *http.Request) {
}
Loading

0 comments on commit 4cfc5c9

Please sign in to comment.