Skip to content

Commit

Permalink
init from starter
Browse files Browse the repository at this point in the history
  • Loading branch information
archmagece committed Feb 23, 2021
0 parents commit 099fde3
Show file tree
Hide file tree
Showing 26 changed files with 574 additions and 0 deletions.
15 changes: 15 additions & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#mode should be "development or production
mode = development
#database details

db_name = test
db_pass = "root"
db_user = user1
db_type = mysql
db_host = localhost
db_port = 3306

port = 8099

#Main URLs
API_URL = http://localhost:8099/api/v1/
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.idea
14 changes: 14 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
language: go

go:
- "1.12"

os:
- linux

dist: trusty
sudo: false
install: true

script:
- unset GOPATH
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 MindInventory

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.
100 changes: 100 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
# Golang Skeleton With Fully Managed Versions For Kick Start GoLang Project Development
<a href="https://travis-ci.org/Mindinventory/Golang-Project-Structure" style="pointer-events: none;" target="_blank"><img src="https://travis-ci.org/Mindinventory/Golang-Project-Structure.svg?branch=master"></a>
<a href="https://godoc.org/fyne.io/fyne" style="pointer-events: none;" target="_blank"><img src="https://img.shields.io/badge/go-documentation-blue.svg"></a>
<a href="https://goreportcard.com/report/github.com/Mindinventory/Golang-Project-Structure" style="pointer-events: none;" target="_blank"><img src="https://goreportcard.com/badge/github.com/Mindinventory/Golang-Project-Structure"></a>
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://github.com/mindinventory/Golang-Project-Structure/blob/master/LICENSE)

There is no doubt that Golang’s good documentation and intelligent features could help developers in learning language efficiently and outcome might be promising still, What Golang is missing is the common structure to quick start any API Structure. While working on several Golang Projects, Golang Developers at Mindinventory confront the requirement of having an effective and well Integrated GoLang API Development Structure and as a result of which they came up with one.

- gorm : It is the ORM library in Go which provides user friendly functions to interact with database. It supports features like ORM, Associations, Hooks, Preloading, Transaction, Auto Migration, Logger etc.
- gin : Gin is a web framework for Go language. Here gin is used for increase performance and productivity.
- godotenv : Basically used for load env variables from .env file.
- mysql : It provides the mysql driver for connecting Go with MySQL.

Check out our blog to know how to use Golang API Skeleton with Fully Managed Versions to kick start Golang project. (https://www.mindinventory.com/blog/golang-project-structure/)


## STRUCTURE

<img src="https://raw.githubusercontent.com/Mindinventory/Golang-Project-Structure/master/structure.png" width=400>


## What it is?

It is a fully managed repository, where one can find all required components in a single package including versioning for REST APIs and you do not need to set up each time they start with any crucial work in Golang.


## Prerequisite

One need to install the latest version of Go i.e 1.12 (Released in Feb 2019) from https://golang.org/dl/ and setup GOROOT and GOPATH.

## Components
<center><img src="https://raw.githubusercontent.com/Mindinventory/Golang-Project-Structure/master/gif.gif"></center>


### 1. ApiHelpers
Basically contains the helper functions used in returning api responses, HTTP status codes, default messages etc.

### 2. Controllers
Contains handler functions for particular route to be called when an api is called.

### 3. Helpers
Contains helper functions used in all apis

### 4. Middlewares
Middleware to be used for the project

### 5. Models
Database tables to be used as models struct

### 6. Resources
Resources contains all structures other than models which can be used as responses

### 7. Routers
Resources define the routes for your project

### 8. Seeder
It is optional, but if you want to insert lots of dummy records in your database, then you can use seeder.

### 9. Services
All the core apis for your projects should be within services.

### 10. Storage
It is generally for storage purpose.

### 11. Templates
Contains the HTML templates used in your project

### 12. .env
Contains environment variables.


## Steps to Follow

. For running the server you have to run following command in the terminal.
```go run main.go
```
It will start your server at the port you have mentioned in the ```.env``` file.

. To run the server in a port other than the default, run following command.
```go run main.go <specific port>```

. To create a build for your project and uploaded in the server, one need to run following command.
```go build```


## API with versioning

# For using version 1 api
```127.0.0.1:8099/api/v1/user-list```

# For using version 2 api
```127.0.0.1:8099/api/v2/user-list```


## LICENSE!

Go Project Structure is [MIT-licensed](https://github.com/mindinventory/Golang-Project-Structure/blob/master/LICENSE)

## Let us know!
We’d be really happy if you sent us links to your projects where you use our component. Just send an email to [email protected] And do let us know if you have any questions or suggestion regarding our work.
8 changes: 8 additions & 0 deletions apiHelpers/ApiResponseMsg.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package apihelpers

const (
//Success as constant
Success = "Success."
//Error as constant
Error = "Error."
)
23 changes: 23 additions & 0 deletions apiHelpers/Response.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package apihelpers

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

//ResponseData structure
type ResponseData struct {
Data interface{} `json:"data"`
Meta interface{} `json:"meta"`
}

//Message returns map data
func Message(status int, message string) map[string]interface{} {
return map[string]interface{}{"status": status, "message": message}
}

//Respond returns basic response structure
func Respond(w http.ResponseWriter, data map[string]interface{}) {
w.Header().Add("Content-Type", "application/json")
json.NewEncoder(w).Encode(data)
}
27 changes: 27 additions & 0 deletions controllers/api/v1/user.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package v1

import (
u "GoProject/apiHelpers"
v1s "GoProject/services/api/v1"
"encoding/json"
"github.com/gin-gonic/gin"
)

//UserList function will give you the list of users
func UserList(c *gin.Context) {
var userService v1s.UserService

//decode the request body into struct and failed if any error occur
err := json.NewDecoder(c.Request.Body).Decode(&userService.User)
if err != nil {
u.Respond(c.Writer, u.Message(1, "Invalid request"))
return
}

//call service
resp := userService.UserList()

//return response using api helper
u.Respond(c.Writer, resp)

}
27 changes: 27 additions & 0 deletions controllers/api/v2/user.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package v2

import (
u "GoProject/apiHelpers"
v2s "GoProject/services/api/v2"
"encoding/json"
"github.com/gin-gonic/gin"
)

//UserList function will give you the list of users
func UserList(c *gin.Context) {
var userService v2s.UserService

//decode the request body into struct and failed if any error occur
err := json.NewDecoder(c.Request.Body).Decode(&userService.User)
if err != nil {
u.Respond(c.Writer, u.Message(1, "Invalid request"))
return
}

//call service
resp := userService.UserList()

//return response using api helper
u.Respond(c.Writer, resp)

}
Binary file added gif.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added gifnew.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
10 changes: 10 additions & 0 deletions helpers/helpers.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package helpers

import (
"strconv"
)

//Int64ToString function convert a float number to a string
func Int64ToString(inputNum int64) string {
return strconv.FormatInt(inputNum, 10)
}
38 changes: 38 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package main

import (
"GoProject/routers"
"fmt"
"github.com/joho/godotenv"
"os"
)

//Execution starts from main function
func main() {

e := godotenv.Load()
if e != nil {
fmt.Print(e)
}
r := Routers.SetupRouter()

port := os.Getenv("port")

// For run on requested port
if len(os.Args) > 1 {
reqPort := os.Args[1]
if reqPort != "" {
port = reqPort
}
}

if port == "" {
port = "8080" //localhost
}
type Job interface {
Run()
}

r.Run(":" + port)

}
15 changes: 15 additions & 0 deletions middlewares/auth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package middlewares

import "github.com/gin-gonic/gin"

/*
UserMiddlewares function to add auth
*/
func UserMiddlewares() gin.HandlerFunc {
return func(c *gin.Context) {

//Code for middlewares

c.Next()
}
}
58 changes: 58 additions & 0 deletions models/base.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package models

import (
"fmt"
"github.com/go-sql-driver/mysql"
"github.com/jinzhu/gorm"
"github.com/joho/godotenv"
"log"
"os"
"time"
)

var db *gorm.DB

//Model is sample of common table structure
type Model struct {
ID uint `gorm:"primary_key" json:"id,omitempty"`
CreatedAt time.Time `gorm:"not null" json:"created_at" sql:"DEFAULT:CURRENT_TIMESTAMP"`
UpdatedAt time.Time `gorm:"not null" json:"updated_at" sql:"DEFAULT:CURRENT_TIMESTAMP"`
DeletedAt *time.Time `sql:"index" json:"deleted_at,omitempty"`
}

func init() {

e := godotenv.Load()
if e != nil {
fmt.Print(e)
}

username := os.Getenv("db_user")
password := os.Getenv("db_pass")
dbName := os.Getenv("db_name")
dbHost := os.Getenv("db_host")
dbPort := os.Getenv("db_port")

msql := mysql.Config{}
log.Println(msql)

conn, err := gorm.Open("mysql", username+":"+password+"@tcp("+dbHost+":"+dbPort+")/"+dbName+"?charset=utf8&parseTime=True&loc=Asia%2FKolkata")

if err != nil {
fmt.Print(err)
}
db = conn

//Printing query
db.LogMode(true)

//Automatically create migration as per model
db.Debug().AutoMigrate(
&User{},
)
}

//GetDB function return the instance of db
func GetDB() *gorm.DB {
return db
}
13 changes: 13 additions & 0 deletions models/user.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package models

//User structure
type User struct {
Model
Name string `gorm:"type:varchar(50)" json:"name" validate:"required"`
Email string `gorm:"type:varchar(50)" json:"email" validate:"required,email"`
}

//TableName return name of database table
func (u *User) TableName() string {
return "user"
}
8 changes: 8 additions & 0 deletions resources/api/v1/user.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package v1resources

//UserResponse struct
type UserResponse struct {
ID uint `json:"id"`
Name string `json:"name,omitempty"`
Email string `json:"email,omitempty" validate:"required,email"`
}
Loading

0 comments on commit 099fde3

Please sign in to comment.