Giter Site home page Giter Site logo

gin-api-template's Introduction

A simple project template based on gin framework

Licence API Log Golang


中文

Overview

A simple project construction template based on the gin framework.

If you want to quickly build a backend project using golang, this template is perfect for you. You can directly use this project and quickly develop your own project based on it.

Architecture Overview

├── cmd
│   ├── apps # Subdirectory for sub-projects`
│   │   ├── config.example.yaml # Example configuration file for startup
│   │   └── server.go # Starts a specific sub-project`
│   └── main.go # The entpoint for starting the project.
├── docs # various documents
│   └── images
└── pkg  # Core code package of the project`
    ├── conf
    │   └── conf.go # Global configuration settings` 
    ├── logger # Logging settings
    ├── server # Core logic block of the project. If there are multiple sub-modules, multiple directories can be created. Here is an example of a server directory is provided.
    │   ├── auth # Authentication module` 
    │   │   └── acl # Default ACL authentication
    │   │   └── ... # Any other authentication can be placed in a separate directory, such as ldap 
    │   ├── controller # Controller module`
    │   │   ├── controller.go # Definition of a global controller
    │   │   └── hello.go # An example API. Each type of API interface should have a separate file for better organization. 
    │   ├── model # Configuration of storage structures, including model configurations for various database storages, such as definitions of database fields, etc.
    │   │   └── hello.go
    │   ├── router # Various router definitions
    │   │   ├── middleware # Definition of various middlewares
    │   │   │   ├── auth.go # Authentication
    │   │   │   ├── cache.go # Cache
    │   │   │   ├── log.go # Logging
    │   │   │   └── ... 
    │   │   ├── router.go # Global router configuration
    │   │   └── routers.go # Configuration of various routes. The main logic of the API code is configured here.
    │   └── storage # Implementation of backend storage`
    │       ├── cache # Cache implementation` 
    │       │   ├── local # In-memory storage
    │       │   └── redis # Redis storage
    │       └── db # Storage for various databases
    │           └── mysql
    └── util # Contains various common functions and utilities
        └── util.go

Features

  • Cobra for command-line startup.
  • Uses YAML format for configuration files.
  • Logging is done using Zap, which provides logging output , log rotation , Dynamically modify the log output level .
  • router configuration.
  • multiple middlewares.

Getting Started

Step 1. Clone the project

git clone [email protected]:veops/gin-api-template.git

Step 2. Modify config file

cd gin-api-template/cmd
cp apps/config.example.yaml apps/config.yaml 
# modify config.yaml

Step 3. Build and run the project

go build -o server main.go 
./server run -c apps

Step 4. Validation

Verify any one of the following is normal.

  • Service availability check, Must-have as an API service
curl -X GET http://localhost:8080/-/health

response is: OK

  • Dynamically modify the log level. This API is convenient for adjusting the log output level dynamically without the need to restart the service, making it easier to troubleshoot issues when encountered.
curl -X PUT localhost:8080/-/log/level -H "Content-Type: application/json" -d '{"level":"debug"}'

response is:

{"level":"debug"}
  • Regular API validation.
curl -X GET http://localhost:8080/api/v1/hello

response is:

{
  "code":0,
  "data":{
    "Time":"2023-11-06T09:36:55.830076+08:00"
  },
  "message":"hello world"
}

FAQ

How can I add new routes(i.e. api)

  1. Write your own handler in pkg/server/controller, just like what hello.go does
  2. Register your handler to routes in pkg/server/router/routes.go

How can I add new middlewares

  1. There all some middlewares providered by default in pkg/server/middlware, therefore, plaease check them firstly. If you do not find what you need, just write your own one here.
  2. Then you should register yours in the setupRouter() function in pkg/server/router

How to use my own authorization

  1. Add your own authorization way in pkg/server/router/middleware/auth.go. ACL, white list and basic auth is provided by default.
  2. Rearrange the order of auth functions if you need in Auth() function

What is ACL

  1. A role-based resource permission management service. Please check defails here https://github.com/veops/acl

How to use my prefered database

  1. Since this project is a common template and cohices of db is much different in different conditions, we did not provide a default one, the folder of mysql is just used to demonstrate.
  2. Suppose you want to add mongo database. You can add a folder in db with a file named mongo.go in it. Then you should finish init logic of mongo.
  3. Add mongo config struct in conf/conf.go
  4. Add mongo config in your config.yaml file

gin-api-template's People

Contributors

fxiang21 avatar ivongwy avatar pycook avatar rickywei avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

gin-api-template's Issues

[Bug]: package main is not in std

Contact Details

No response

This bug is related to UI or API?

No response

What happened?

A bug happened!

Version

newest

What browsers are you seeing the problem on?

No response

Relevant log output

No response

[help wanted]: 使用 postman 发送 post 请求,使用 raw 源的 json 数据,无法绑定到结构体

Contact Details

No response

What is your question?

我使用postman 发送 post 请求,数据源是 raw, json 结构。 但是无论怎样,都无法使用 gin 的 ShouldBind 以及 ShouldBindJson 获取到发送的数据,下面是我的代码:

package controller

type SmsParams struct {
	UserMobile string `json:"userMobile" form:"userMobile" uri:"userMobile" xml:"userMobile" binding:"required"`
}
func (c *Controller) SmsController(ctx *gin.Context) {
	var respMap = make(map[string]interface{})

	// 解析参数
	raw := &SmsParams{}
	bindErr := ctx.ShouldBind(raw)
	if bindErr != nil {
		FailureResponse(ctx, bindErr.Error())
		return
	}

	fmt.Println("smsParams-->", raw)
	SuccessResponse(ctx)
}

下面是 postman 设置:
image

下面是输出日志:

image

请问有哪里需要调整?

Version

newest

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.