Skip to content

Instantly share code, notes, and snippets.

@WoolWarrior
Last active September 7, 2019 07:28
Show Gist options
  • Save WoolWarrior/3b95a0c0579af53c040c80081a7e7c98 to your computer and use it in GitHub Desktop.
Save WoolWarrior/3b95a0c0579af53c040c80081a7e7c98 to your computer and use it in GitHub Desktop.
qor-admin replacing sqlite3 with dummy object - 2nd attempt (worked)
package main
import (
"database/sql"
"fmt"
"net/http"
"time"
"github.com/getlantern/deepcopy"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
"github.com/qor/admin"
"github.com/qor/qor"
"github.com/qor/qor/resource"
"github.com/qor/roles"
)
// Define a GORM-backend model
type User struct {
gorm.Model
Email string
Password string
Name sql.NullString
Gender string
Role string
Addresses string
}
// Define another GORM-backend model
type Product struct {
// gorm.Model
ID uint `gorm:"primary_key"`
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt *time.Time `sql:"index"`
Name string
Description string
}
func main() {
// Set up the database
DB, _ := gorm.Open("sqlite3", "demo.db")
DB.AutoMigrate(&User{}, &Product{})
// Initalize
Admin := admin.New(&admin.AdminConfig{
SiteName: "Admin Panel",
DB: DB})
// Create resources from GORM-backend model
Admin.AddResource(&User{}, &admin.Config{Menu: []string{"User Management"}})
p := Admin.AddResource(&Product{})
p.FindOneHandler = func(result interface{}, metaValues *resource.MetaValues, context *qor.Context) error {
var product101 Product
product101.ID = 101
product101.Name = "phone101"
product101.Description = "phone101"
product101.CreatedAt = time.Now()
product101.UpdatedAt = time.Now()
res := p
if res.HasPermission(roles.Read, context) {
var (
primaryQuerySQL string
primaryParams []interface{}
)
if metaValues == nil {
primaryQuerySQL, primaryParams = res.ToPrimaryQueryParams(context.ResourceID, context)
} else {
primaryQuerySQL, primaryParams = res.ToPrimaryQueryParamsFromMetaValue(metaValues, context)
}
fmt.Println("ResourceID, primaryParams, primaryQuerySQL: ", context.ResourceID, primaryParams, primaryQuerySQL)
fmt.Println("1.result, &result: ", result, &result)
deepcopy.Copy(result, product101) // equal to below code
// var buf bytes.Buffer
// json.NewEncoder(&buf).Encode(product101)
// json.NewDecoder(bytes.NewBuffer(buf.Bytes())).Decode(&result)
return nil
}
return nil
}
// Initalize an HTTP request multiplexer
mux := http.NewServeMux()
// Mount admin to the mux
Admin.MountTo("/admin", mux)
fmt.Println("Listening on: 9000")
http.ListenAndServe(":9000", mux)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment