Last active
April 1, 2016 14:14
-
-
Save yanmhlv/5ad9b148242eef0e9339 to your computer and use it in GitHub Desktop.
simple query controller, handle GET-params
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"log" | |
"time" | |
"github.com/gin-gonic/gin" | |
"github.com/jinzhu/gorm" | |
) | |
var db *gorm.DB | |
// ModelQuerer interface for GET-queries | |
type ModelQuerer interface { | |
ExcludeFields() []string | |
TableName() string | |
BuildQuery() string | |
} | |
// User user model | |
type User struct { | |
ID uint | |
Email string | |
Password string | |
Birthdate *time.Time | |
} | |
// ExcludeFields exclude fields | |
func (u *User) ExcludeFields() []string { | |
return []string{"email"} | |
} | |
// TableName table name | |
func (u *User) TableName() string { | |
return "users" | |
} | |
func (u *User) BuildQuery(fieldName string, value string) string { | |
return fmt.Sprintf("%s = ?") | |
} | |
// QueryMiddleware middleware for GET-query | |
func QueryMiddleware(model ModelQuerer) gin.HandlerFunc { | |
return func(c *gin.Context) { | |
c.Next() | |
if c.IsAborted() { | |
return | |
} | |
scope, exists := c.Get("scope") | |
if !exists { | |
return | |
} | |
db.Table(model.TableName()).Raw(scope) | |
// .Find(&values) | |
// c.JSON(200, values) | |
c.JSON(200, map[string]string{"result": "hello"}) | |
} | |
} | |
func main() { | |
var err error | |
db, err = gorm.Open("postgres", "user=gorm password=123 dbname=gorm sslmode=disable") | |
if err != nil { | |
log.Panicln(err) | |
} | |
app := gin.Default() | |
app.GET("/users", QueryMiddleware(&User{}), func(c *gin.Context) { | |
// c.Set("scope", db.Where("is_active = ?", true)) | |
}) | |
app.Run(":3000") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment