Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/cuongnb14/gin-builder
Build your powerful gin API quickly
https://github.com/cuongnb14/gin-builder
gin gin-builder gin-helper gorm-filter
Last synced: 19 days ago
JSON representation
Build your powerful gin API quickly
- Host: GitHub
- URL: https://github.com/cuongnb14/gin-builder
- Owner: cuongnb14
- Created: 2024-08-22T06:37:07.000Z (4 months ago)
- Default Branch: main
- Last Pushed: 2024-08-23T02:20:32.000Z (4 months ago)
- Last Synced: 2024-11-20T17:42:13.075Z (about 1 month ago)
- Topics: gin, gin-builder, gin-helper, gorm-filter
- Language: Go
- Homepage:
- Size: 19.5 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Gin builder
## Package
- `apierror`: Define `APIError` struct that handle by `error_handler` middleware
- `gormfilter`: Auto build gorm query base on gin request param
- `pagination`: Auto paging gorm query
- `handlerbuilder`: Build CURD api base on gorm model (like django style)## Usage
```go
package testsimport (
"fmt"
"github.com/cuongnb14/gin-builder/gormfilter"
"github.com/cuongnb14/gin-builder/handlerbuilder"
"github.com/cuongnb14/gin-builder/pagination"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"gorm.io/gorm"
"net/http"
"net/http/httptest"
"testing"
)/*
Url filter like: /users?min_age=10&[email protected]
*/
func NewUserFilter() *gormfilter.FilterBuilder {
filterBuilder := &gormfilter.FilterBuilder{}
filterBuilder.
AddFilter(gormfilter.Filter[string]{
Param: "min_age",
Field: "age",
Op: gormfilter.Gte,
}).
AddFilter(gormfilter.Filter[string]{
Param: "email",
Field: "email",
Op: gormfilter.Eq,
}).
SetOrdering([]string{"age", "name"})
return filterBuilder
}func Test_HandlerBuilder(t *testing.T) {
gin.SetMode(gin.TestMode)db := GetDB()
defer func() {
sqlDB, _ := db.DB()
_ = sqlDB.Close()
}()CreateUser(db, 5)
router := gin.Default()
userHandlerBuilder := handlerbuilder.HandlerBuilder[User, UserVO]{
FnGetQuery: func(c *gin.Context) *gorm.DB {
return db.Model(&User{})
},
FilterBuilder: NewUserFilter(),
Pagination: pagination.NewStandardPagination(),
}router.GET("/users", userHandlerBuilder.BuildListHandler())
router.GET("/users/:id", userHandlerBuilder.BuildRetrieveHandler())t.Run("List users", func(t *testing.T) {
req, _ := http.NewRequest(http.MethodGet, "/users?min_age=44", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)assert.Equal(t, http.StatusOK, w.Code)
fmt.Println(string(w.Body.Bytes()))
assert.Contains(t, w.Body.String(), "\"total\":1")
})t.Run("Retrieve user", func(t *testing.T) {
req, _ := http.NewRequest(http.MethodGet, "/users/1", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)assert.Equal(t, http.StatusOK, w.Code)
fmt.Println(string(w.Body.Bytes()))
assert.Contains(t, w.Body.String(), "User 1")
})
}```