Skip to content

Commit

Permalink
Adjusted middleware file
Browse files Browse the repository at this point in the history
  • Loading branch information
jsdaniell committed Mar 22, 2021
1 parent 371a086 commit 92bb772
Show file tree
Hide file tree
Showing 842 changed files with 131,157 additions and 14 deletions.
803 changes: 802 additions & 1 deletion .idea/workspace.xml

Large diffs are not rendered by default.

103 changes: 103 additions & 0 deletions bin/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
# recipe-cli
> The fastest and easy way to generate boilerplate projects with structure for production-ready.
### Why use *recipe-cli* instead common technologies' cli?

- Projects structured to different use cases.
- Diferent platform deployment and CI CD Scripts configured.
- Built-in helper scripts (build.sh in some projects).
- Self-learning helper comments (Detailed instructions to customize the files, like instructions to controllers, views, models)

### Installing

To install you can use npm to get globally on your machine:

`npm i -g recipe-cli`

After this you can get the list of project typing `recipe-cli` or init some project with `recipe-cli {language}`, like:

`recipe-cli golang`

A bunch of options will be showed to configure your project.

## Golang Projects Boilerplates

**1. API Project Structure (Mux Router)**

- Two database pre-configured configurations and models (Firebase || MongoDB) || Empty structure.
- Heroku configuration files and build scripts.
- MVP Project Structure with routes example, ready to customize.
- Utilities package for JSON responses and Token validation already created.
- Pre-configured Github Action script for deploy on heroku.
- Pre-configured CORS.

```
project
├── Procfile
├── api
│ ├── controllers
│ │ └── entity.go (controller used on entity_routes inside routes package)
│ ├── db
│ │ └── database.go (database connection - Firebase || MongoDB || Empty)
│ ├── middlewares
│ │ └── middlewares.go (middleware functions to deal with cors configuration)
│ ├── models
│ │ ├── Entity.go (example of model in accord with database choosed)
│ │ └── Token.go (token model to be used with token validation function in security package)
│ ├── repository
│ │ └── entity_repository (example of repository function used inside controllers)
│ ├── responses
│ │ └── responses.go (utility to format JSON responses from the API)
│ ├── router
│ │ ├── router.go
│ │ └── routes (route pre-configured for each controller)
│ ├── server.go
│ └── utils
│ ├── json_utility (utility to work with Structs -> JSON management)
│ └── security (utility for validate token)
├── build.sh
├── config
│ └── config.go
├── deploy_to_heroku.sh (deploy to heroku with sh deploy_to_heroku.sh file)
├── go.mod
├── go.sum
├── heroku.yml (heroku configuration file for go projects)
├── main.go
└── vendor (vendoring of the dependencies)
...
30 directories, 17 files
```

**2. CLI Project Structure**

- Utilities for command-line interface, like **selectors** and input user commands with validation.
- Utility to integrate shell commands inside your application.
- Pre-configured release configuration and script.
- CI CD Scripts for publish release pre-configured.
- Deploy and release with `git tag -a v1.0.0 -m "Alpha Release" && git push origin v1.0.0` (the version have to be the same of package.json)
- NPM deploy script configured, production-ready, publish with `npm publish`.

```
project
├── cli
│ ├── selector_cli.go (selector cli interface)
│ └── user_input.go (user input cli interface with validation)
├── cmd
│ ├── other_command (example of declaring subcommand)
│ │ └── other_command.go
│ └── root.go
├── go.mod
├── go.sum
├── main.go
├── package.json
├── utils (go commands utilities and shell commands utilities)
│ ├── go_commands
│ │ ├── go_mod.go
│ │ └── shell_commands.go
│ └── shell_commands
└── vendor
...
27 directories, 11 files
```
Binary file removed bin/recipe-cli
Binary file not shown.
24 changes: 12 additions & 12 deletions cmd/golang/golang_api/go_content_files/api_middewares.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@ func writeMiddlewaresFile(username, projectName string){
package middlewares
import (
\"fmt\"
\"github.com/`+ username +`/`+ projectName +`/api/responses\"
\"log\"
\"net/http\"
"fmt"
"github.com/`+ username +`/`+ projectName +`/api/responses"
"log"
"net/http"
)
// Validate Access Control to API and deal with CORS request.
Expand All @@ -32,14 +32,14 @@ func SetMiddlewareLogger(next http.HandlerFunc) http.HandlerFunc {
// TODO: When in production setup to https://website
w.Header().Set(\"Access-Control-Allow-Origin\", \"*\")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set(\"Access-Control-Allow-Headers\", \"Content-Type, Authorization\")
w.Header().Set(\"Access-Control-Allow-Methods\", \"*\")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
w.Header().Set("Access-Control-Allow-Methods", "*")
log.Println(\"%s %s%s %s\", r.Method, r.Host, r.RequestURI, r.Proto)
log.Println("%s %s%s %s", r.Method, r.Host, r.RequestURI, r.Proto)
if (*r).Method == \"OPTIONS\" {
if (*r).Method == "OPTIONS" {
return
}
Expand All @@ -52,9 +52,9 @@ func SetMiddlewareJSON(next http.HandlerFunc, openRoute bool) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if !openRoute {
auth := r.Header.Get(\"Authorization\")
if auth == \"\" {
responses.ERROR(w, http.StatusBadRequest, fmt.Errorf(\"missing authorization token\"))
auth := r.Header.Get("Authorization")
if auth == "" {
responses.ERROR(w, http.StatusBadRequest, fmt.Errorf("missing authorization token"))
return
}
}
Expand Down
1 change: 1 addition & 0 deletions fire/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
API_PORT=9000
21 changes: 21 additions & 0 deletions fire/.github/workflows/deploy.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
name: Heroku CI - CD

on:
push:
branches: [ master ]

jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@master
- uses: actions/setup-go@v1
with:
go-version: '1.14.6'
- run: go mod vendor
- run: git config --global user.email "putYourEmail" && git config --global user.name "${username}"
- uses: akhileshns/[email protected]
with:
heroku_api_key: \${{ secrets.HEROKU_API_KEY }}
heroku_app_name: "${nameProject}"
heroku_email: "putYourEmail"
1 change: 1 addition & 0 deletions fire/Procfile
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
web: bin/fire
37 changes: 37 additions & 0 deletions fire/api/controllers/entity.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package controllers

import (
"encoding/json"
"github.com/jsdaniell/fire/api/models"
"github.com/jsdaniell/fire/api/repository/entity_repository"
"github.com/jsdaniell/fire/api/responses"
"io/ioutil"
"net/http"
)

// AddEntityController is the entity function for a controller
func AddEntityController(w http.ResponseWriter, r *http.Request) {
var entity models.Entity

// auth := r.Header.Get("Authorization")

bytes, err := ioutil.ReadAll(r.Body)
if err != nil {
responses.ERROR(w, http.StatusUnprocessableEntity, err)
return
}

err = json.Unmarshal(bytes, &entity)
if err != nil {
responses.ERROR(w, http.StatusUnprocessableEntity, err)
return
}

entityAdded := entity_repository.AddEntity(entity)
if err != nil {
responses.ERROR(w, http.StatusUnprocessableEntity, err)
return
}

responses.JSON(w, http.StatusOK, entityAdded)
}
3 changes: 3 additions & 0 deletions fire/api/db/database.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
package db

// Put your database connection here.
47 changes: 47 additions & 0 deletions fire/api/middlewares/middlewares.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// Middlewares to handle generic handles of request.
package middlewares

import (
\"fmt\"
\"github.com/jsdaniell/fire/api/responses\"
\"log\"
\"net/http\"
)

// Validate Access Control to API and deal with CORS request.
func SetMiddlewareLogger(next http.HandlerFunc) http.HandlerFunc {

return func(w http.ResponseWriter, r *http.Request) {

// TODO: When in production setup to https://website

w.Header().Set(\"Access-Control-Allow-Origin\", \"*\")

w.Header().Set(\"Access-Control-Allow-Headers\", \"Content-Type, Authorization\")
w.Header().Set(\"Access-Control-Allow-Methods\", \"*\")

log.Println(\"%s %s%s %s\", r.Method, r.Host, r.RequestURI, r.Proto)

if (*r).Method == \"OPTIONS\" {
return
}

next(w, r)
}
}

// Middleware to test authorization header parameter on closed routes.
func SetMiddlewareJSON(next http.HandlerFunc, openRoute bool) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {

if !openRoute {
auth := r.Header.Get(\"Authorization\")
if auth == \"\" {
responses.ERROR(w, http.StatusBadRequest, fmt.Errorf(\"missing authorization token\"))
return
}
}

next(w, r)
}
}
8 changes: 8 additions & 0 deletions fire/api/models/Entity.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package models

// Entity model used to receive request and send JSON response, is used on authentication controller.
type Entity struct {
ID string `json:"_id"`
Name string `json:"name, omitempty"`
Description string `json: "description"`
}
7 changes: 7 additions & 0 deletions fire/api/models/Token.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package models

// User model used to receive request and send JSON response, is used on authentication controller.
type Token struct {
CreatedAt string `json:"created_at,omitempty"`
Token string `json:"token,omitempty"`
}
3 changes: 3 additions & 0 deletions fire/api/repository/entity_repository/entity_repository.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
package entity_repository

// Put your database functions of specific entity here.
32 changes: 32 additions & 0 deletions fire/api/responses/responses.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Response utility to returns JSON error or JSON response to the request.
package responses

import (
"encoding/json"
"fmt"
"net/http"
)

func JSON(w http.ResponseWriter, statusCode int, data interface{}) {
w.WriteHeader(statusCode)

w.Header().Set("Content-Type", "application/json")

err := json.NewEncoder(w).Encode(data)
if err != nil {
fmt.Fprintf(w, "%s", err.Error())
}
}

func ERROR(w http.ResponseWriter, statusCode int, err error) {
if err != nil {
JSON(w, statusCode, struct {
Error string`json:"error"`
}{
Error: err.Error(),
})
return
}

JSON(w, http.StatusBadRequest, nil)
}
13 changes: 13 additions & 0 deletions fire/api/router/router.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// Router setup.
package router

import (
"github.com/gorilla/mux"
"github.com/jsdaniell/fire/api/router/routes"
)

func New() *mux.Router {
r := mux.NewRouter().StrictSlash(true)

return routes.SetupRoutesWithMiddlewares(r)
}
21 changes: 21 additions & 0 deletions fire/api/router/routes/entity_routes.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package routes

import (
"github.com/jsdaniell/fire/api/controllers"
"net/http"
)

var entityRoutes = []Route{
{
URI: "/addEntity",
Method: http.MethodPost,
Handler: controllers.AddEntityController,
Open: true,
},
// Route{
// Uri: "/deleteEntity/{code}",
// Method: http.MethodDelete,
// Handler: controllers.DeleteProductController,
// Open: true,
// },
}
Loading

0 comments on commit 92bb772

Please sign in to comment.