Go
プロジェクト構造に関するベストプラクティス
サーチ…
GinによるRestfullプロジェクトAPI
GinはGolangで書かれたWebフレームワークです。これは、より良いパフォーマンスで最大40倍高速のマティーニのようなAPIを備えています。パフォーマンスと生産性が必要な場合は、ジンが大好きです。
8つのパッケージ+ main.goがあります
- コントローラ
- コア
- libs
- ミドルウェア
- パブリック
- ルータ
- サービス
- テスト
- main.go
コントローラ
コントローラパッケージにはすべてのAPIロジックが格納されます。あなたのAPIが何であれ、あなたのロジックはここで起こりますコア
コアパッケージには、作成したすべてのモデル、ORMなどが格納されます。libs
このパッケージは、プロジェクトで使用されたライブラリをすべて格納します。しかし、手作業で作成/インポートされたライブラリの場合にのみ、go get package_nameコマンドを使用go get package_name利用できません。あなた自身のハッシュアルゴリズム、グラフ、ツリーなどである可能性があります。 ミドルウェア
このパッケージは、プロジェクトで使用されているすべてのミドルウェアを格納し、cors、device-id、authなどの作成/検証が可能ですパブリック
このpacakgeはすべてのパブリックおよび静的ファイルを保存し、html、css、javascript、imagesなどになります。ルータ
このパッケージは、REST APIのすべてのルートを保存します。ルートを割り当てる方法のサンプルコードを参照してください。
auth_r.go
import (
auth "simple-api/controllers/v1/auth"
"gopkg.in/gin-gonic/gin.v1"
)
func SetAuthRoutes(router *gin.RouterGroup) {
/**
* @api {post} /v1/auth/login Login
* @apiGroup Users
* @apiHeader {application/json} Content-Type Accept application/json
* @apiParam {String} username User username
* @apiParam {String} password User Password
* @apiParamExample {json} Input
* {
* "username": "your username",
* "password" : "your password"
* }
* @apiSuccess {Object} authenticate Response
* @apiSuccess {Boolean} authenticate.success Status
* @apiSuccess {Integer} authenticate.statuscode Status Code
* @apiSuccess {String} authenticate.message Authenticate Message
* @apiSuccess {String} authenticate.token Your JSON Token
* @apiSuccessExample {json} Success
* {
* "authenticate": {
* "statuscode": 200,
* "success": true,
* "message": "Login Successfully",
* "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ"
* }
* }
* @apiErrorExample {json} List error
* HTTP/1.1 500 Internal Server Error
*/
router.POST("/auth/login" , auth.Login)
}
私がハンドラを分ける理由は、各ルータを簡単に管理できることです。 APIについてのコメントを作成できます。apidocを使用すると、構造化されたドキュメントにこれを生成できます。それから、現在のパッケージでindex.goの関数を呼び出します
index.go
package v1
import (
"gopkg.in/gin-gonic/gin.v1"
token "simple-api/middlewares/token"
appid "simple-api/middlewares/appid"
)
func InitRoutes(g *gin.RouterGroup) {
g.Use(appid.AppIDMiddleWare())
SetHelloRoutes(g)
SetAuthRoutes(g) // SetAuthRoutes invoked
g.Use(token.TokenAuthMiddleWare()) //secure the API From this line to bottom with JSON Auth
g.Use(appid.ValidateAppIDMiddleWare())
SetTaskRoutes(g)
SetUserRoutes(g)
}
サービス
このパッケージは、使用されているサービスからプロジェクトで使用する設定や設定を保存します。mongodb、redis、mysql、elasticsearchなどがあります。main.go
APIの主要入口です。 dev環境設定、システム、ポートなどの設定はここで設定します。例:
main.go
package main
import (
"fmt"
"net/http"
"gopkg.in/gin-gonic/gin.v1"
"articles/services/mysql"
"articles/routers/v1"
"articles/core/models"
)
var router *gin.Engine;
func init() {
mysql.CheckDB()
router = gin.New();
router.NoRoute(noRouteHandler())
version1:=router.Group("/v1")
v1.InitRoutes(version1)
}
func main() {
fmt.Println("Server Running on Port: ", 9090)
http.ListenAndServe(":9090",router)
}
func noRouteHandler() gin.HandlerFunc{
return func(c *gin.Context) {
var statuscode int
var message string = "Not Found"
var data interface{} = nil
var listError [] models.ErrorModel = nil
var endpoint string = c.Request.URL.String()
var method string = c.Request.Method
var tempEr models.ErrorModel
tempEr.ErrorCode = 4041
tempEr.Hints = "Not Found !! \n Routes In Valid. You enter on invalid Page/Endpoint"
tempEr.Info = "visit http://localhost:9090/v1/docs to see the available routes"
listError = append(listError,tempEr)
statuscode = 404
responseModel := &models.ResponseModel{
statuscode,
message,
data,
listError,
endpoint,
method,
}
var content gin.H = responseModel.NewResponse();
c.JSON(statuscode,content)
}
}
ps:この例のすべてのコードは、異なるプロジェクトから来ています
Modified text is an extract of the original Stack Overflow Documentation
ライセンスを受けた CC BY-SA 3.0
所属していない Stack Overflow







