Skip to content

Commit

Permalink
Merge pull request GoAdminGroup#449 from eavesmy/gear
Browse files Browse the repository at this point in the history
feat(adapter): add Gear support
  • Loading branch information
cg33 authored Feb 14, 2022
2 parents e187dcb + 8df6c91 commit e031b8d
Show file tree
Hide file tree
Showing 7 changed files with 415 additions and 98 deletions.
196 changes: 196 additions & 0 deletions adapter/gear/gear.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
/***
# File Name: ../../adapter/gear/gear.go
# Author: eavesmy
# Email: [email protected]
# Created Time: 2021年06月03日 星期四 19时05分06秒
***/

package gear

import (
"bytes"
"errors"
"net/http"
"net/url"
"strings"

"github.com/GoAdminGroup/go-admin/adapter"
"github.com/GoAdminGroup/go-admin/context"
"github.com/GoAdminGroup/go-admin/engine"
"github.com/GoAdminGroup/go-admin/modules/config"
"github.com/GoAdminGroup/go-admin/plugins"
"github.com/GoAdminGroup/go-admin/plugins/admin/models"
"github.com/GoAdminGroup/go-admin/plugins/admin/modules/constant"
"github.com/GoAdminGroup/go-admin/template/types"
"github.com/teambition/gear"
)

// Gear structure value is a Gin GoAdmin adapter.
type Gear struct {
adapter.BaseAdapter
ctx *gear.Context
app *gear.App
router *gear.Router
}

func init() {
engine.Register(new(Gear))
}

// User implements the method Adapter.User.
func (gears *Gear) User(ctx interface{}) (models.UserModel, bool) {
return gears.GetUser(ctx, gears)
}

// Use implements the method Adapter.Use.
func (gears *Gear) Use(app interface{}, plugs []plugins.Plugin) error {
return gears.GetUse(app, plugs, gears)
}

// Content implements the method Adapter.Content.
func (gears *Gear) Content(ctx interface{}, getPanelFn types.GetPanelFn, fn context.NodeProcessor, btns ...types.Button) {
gears.GetContent(ctx, getPanelFn, gears, btns, fn)
}

type HandlerFunc func(ctx *gear.Context) (types.Panel, error)

func Content(handler HandlerFunc) gear.Middleware {
return func(ctx *gear.Context) error {
engine.Content(ctx, func(ctx interface{}) (types.Panel, error) {
return handler(ctx.(*gear.Context))
})
return nil
}
}

func (gears *Gear) Run() error { panic("not implement") }
func (gears *Gear) DisableLog() { panic("not implement") }
func (gears *Gear) Static(prefix, path string) { panic("not implement") }

// SetApp implements the method Adapter.SetApp.
func (gears *Gear) SetApp(app interface{}) error {
gears.app = app.(*gear.App)
gears.router = gear.NewRouter()
var (
eng *gear.App
ok bool
)
if eng, ok = app.(*gear.App); !ok {
return errors.New("beego adapter SetApp: wrong parameter")
}
gears.app = eng
return nil
}

// AddHandler implements the method Adapter.AddHandler.
func (gears *Gear) AddHandler(method, path string, handlers context.Handlers) {

if gears.router == nil {
gears.router = gear.NewRouter()
}

gears.router.Handle(strings.ToUpper(method), path, func(c *gear.Context) error {

// gears.ctx = c
ctx := context.NewContext(c.Req)

if res, err := c.Any(2); err == nil {
for paramKey, paramValue := range res.(map[string]string) {
if c.Req.URL.RawQuery == "" {
c.Req.URL.RawQuery += strings.ReplaceAll(paramKey, ":", "") + "=" + paramValue
} else {
c.Req.URL.RawQuery += "&" + strings.ReplaceAll(paramKey, ":", "") + "=" + paramValue
}
}
}

ctx.SetHandlers(handlers).Next()

for key, head := range ctx.Response.Header {
c.Res.Header().Add(key, head[0])
}

// fmt.Println("检查头", c.Res.Header(), "\n", ctx.Response.Header)

if ctx.Response.Body != nil {
buf := new(bytes.Buffer)
_, _ = buf.ReadFrom(ctx.Response.Body)

return c.End(ctx.Response.StatusCode, buf.Bytes())
}

return nil
})

gears.app.UseHandler(gears.router)
}

// Name implements the method Adapter.Name.
func (gears *Gear) Name() string {
return "gear"
}

// SetContext implements the method Adapter.SetContext.
func (gears *Gear) SetContext(contextInterface interface{}) adapter.WebFrameWork {
var (
ctx *gear.Context
ok bool
)

if ctx, ok = contextInterface.(*gear.Context); !ok {
panic("gear adapter SetContext: wrong parameter")
}

return &Gear{ctx: ctx}
}

// Redirect implements the method Adapter.Redirect.
func (gears *Gear) Redirect() {
gears.ctx.Redirect(config.Url(config.GetLoginUrl()))
}

// SetContentType implements the method Adapter.SetContentType.
func (gears *Gear) SetContentType() {
gears.ctx.Res.Header().Set("Content-Type", gears.HTMLContentType())
}

// Write implements the method Adapter.Write.
func (gears *Gear) Write(body []byte) {
gears.ctx.End(http.StatusOK, body)
}

// GetCookie implements the method Adapter.GetCookie.
func (gears *Gear) GetCookie() (string, error) {
return gears.ctx.Cookies.Get(gears.CookieKey())
}

// Lang implements the method Adapter.Lang.
func (gears *Gear) Lang() string {
return gears.ctx.Req.URL.Query().Get("__ga_lang")
}

// Path implements the method Adapter.Path.
func (gears *Gear) Path() string {
return gears.ctx.Req.URL.Path
}

// Method implements the method Adapter.Method.
func (gears *Gear) Method() string {
return gears.ctx.Req.Method
}

// FormParam implements the method Adapter.FormParam.
func (gears *Gear) FormParam() url.Values {
_ = gears.ctx.Req.ParseMultipartForm(32 << 20)
return gears.ctx.Req.PostForm
}

// IsPjax implements the method Adapter.IsPjax.
func (gears *Gear) IsPjax() bool {
return gears.ctx.Req.Header.Get(constant.PjaxHeader) == "true"
}

// Query implements the method Adapter.Query.
func (gears *Gear) Query() url.Values {
return gears.ctx.Req.URL.Query()
}
111 changes: 111 additions & 0 deletions examples/gear/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
package main

import (
"log"
"os"
"os/signal"

_ "github.com/GoAdminGroup/go-admin/adapter/gear"
_ "github.com/GoAdminGroup/go-admin/modules/db/drivers/mysql"
_ "github.com/GoAdminGroup/themes/sword"
"github.com/teambition/gear"

"github.com/GoAdminGroup/go-admin/engine"
"github.com/GoAdminGroup/go-admin/examples/datamodel"
"github.com/GoAdminGroup/go-admin/modules/config"
"github.com/GoAdminGroup/go-admin/modules/language"
"github.com/GoAdminGroup/go-admin/plugins/example"
"github.com/GoAdminGroup/go-admin/template"
"github.com/GoAdminGroup/go-admin/template/chartjs"
"github.com/GoAdminGroup/themes/adminlte"
"github.com/teambition/gear/middleware/static"
)

func main() {

app := gear.New()

e := engine.Default()

cfg := config.Config{
Env: config.EnvLocal,
Databases: config.DatabaseList{
"default": {
Host: "127.0.0.1",
Port: "3306",
User: "root",
Pwd: "root",
Name: "godmin",
MaxIdleCon: 50,
MaxOpenCon: 150,
Driver: config.DriverMysql,

//Driver: config.DriverSqlite,
//File: "../datamodel/admin.db",
},
},
Store: config.Store{
Path: "./uploads",
Prefix: "uploads",
},
UrlPrefix: "admin",
Language: language.CN,
IndexUrl: "/",
Debug: true,
AccessAssetsLogOff: true,
Animation: config.PageAnimation{
Type: "fadeInUp",
},
ColorScheme: adminlte.ColorschemeSkinBlack,
BootstrapFilePath: "./../datamodel/bootstrap.go",
}

template.AddComp(chartjs.NewChart())

// customize a plugin

examplePlugin := example.NewExample()

// load from golang.Plugin
//
// examplePlugin := plugins.LoadFromPlugin("../datamodel/example.so")

// customize the login page
// example: https://github.com/GoAdminGroup/demo.go-admin.cn/blob/master/main.go#L39
//
// template.AddComp("login", datamodel.LoginPage)

// load config from json file
//
// e.AddConfigFromJSON("../datamodel/config.json")

app.Use(static.New(static.Options{Root: "./uploads", Prefix: "uploads"}))

if err := e.AddConfig(&cfg).
AddGenerators(datamodel.Generators).
// add generator, first parameter is the url prefix of table when visit.
// example:
//
// "user" => http://localhost:9033/admin/info/user
//
AddGenerator("user", datamodel.GetUserTable).
AddDisplayFilterXssJsFilter().
AddPlugins(examplePlugin).
Use(app); err != nil {
panic(err)
}

// customize your pages

e.HTML("GET", "/admin", datamodel.GetContent)

go func() {
app.Start(":8099")
}()

quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt)
<-quit
log.Print("closing database connection")
e.MysqlConnection().Close()
}
3 changes: 3 additions & 0 deletions modules/db/postgresql.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package db

import (
"database/sql"
"fmt"
"strconv"
"strings"

Expand Down Expand Up @@ -96,6 +97,8 @@ func (db *Postgresql) InitDB(cfgList map[string]config.Database) Connection {
db.Once.Do(func() {
for conn, cfg := range cfgList {

fmt.Println("检查 pg 配置", cfg.GetDSN())

sqlDB, err := sql.Open("postgres", cfg.GetDSN())
if err != nil {
if sqlDB != nil {
Expand Down
2 changes: 1 addition & 1 deletion modules/db/statement.go
Original file line number Diff line number Diff line change
Expand Up @@ -544,7 +544,7 @@ func (sql *SQL) Exec() (int64, error) {
return res.LastInsertId()
}

const postgresInsertCheckTableName = "goadmin_menu|goadmin_permissions|goadmin_roles|goadmin_users|goadmin_user_permissions|goadmin_role_users|goadmin_role_menu|goadmin_role_permissions|goadmin_role_menu"
const postgresInsertCheckTableName = "goadmin_menu|goadmin_permissions|goadmin_roles|goadmin_users"

// Insert exec the insert method of given key/value pairs.
func (sql *SQL) Insert(values dialect.H) (int64, error) {
Expand Down
Loading

0 comments on commit e031b8d

Please sign in to comment.