结构体:

package mainimport ("fmt""net/http""github.com/qor/admin""github.com/jinzhu/gorm"_ "github.com/jinzhu/gorm/dialects/mysql"//windows需要下载 http://tdm-gcc.tdragon.net/download)// 用户type User struct {gorm.ModelName string}// 产品type Product struct {gorm.ModelName stringDescription string}/*自定义结构可继承接口 重命名resource.Nametype ResourceNamer interface {ResourceName() string}*/func main() {// 注册数据库,可以是sqlite3 也可以是 mysql 换下驱动就可以了。mysql_url := "root:mariadb@tcp(175.24.244.132:3306)/qor_test?charset=utf8&parseTime=True&loc=Local"DB, _ := gorm.Open("mysql", mysql_url)DB.AutoMigrate(&User{}, &Product{}) //自动创建表。// 初始化admin 还有其他的,比如APIAdmin := admin.New(&admin.AdminConfig{DB: DB})// 创建admin后台对象资源。Admin.AddResource(&User{})Admin.AddResource(&Product{})// 启动服务mux := http.NewServeMux()Admin.MountTo("/admin", mux)fmt.Println("Listening on: 9000")http.ListenAndServe(":9000", mux)}
func New(config interface{}) *Admin {admin := Admin{funcMaps: make(template.FuncMap),router: newRouter(),metaConfigorMaps: defaultMetaConfigorMaps,}if c, ok := config.(*qor.Config); ok {admin.AdminConfig = &AdminConfig{DB: c.DB}} else if c, ok := config.(*AdminConfig); ok {admin.AdminConfig = c} else {admin.AdminConfig = &AdminConfig{}}if admin.SessionManager == nil {admin.SessionManager = manager.SessionManager}if admin.Transformer == nil {admin.Transformer = DefaultTransformer}if admin.AssetFS == nil {admin.AssetFS = assetfs.AssetFS().NameSpace("admin")}if admin.SettingsStorage == nil {admin.SettingsStorage = newSettings(admin.AdminConfig.DB)}admin.SetAssetFS(admin.AssetFS)if admin.AdminConfig.DB != nil {admin.AdminConfig.DB.AutoMigrate(&QorAdminSetting{})}admin.registerCompositePrimaryKeyCallback()return &admin}
debug
*github.com/qor/admin.Admin {AdminConfig: *github.com/qor/admin.AdminConfig {SiteName: "QExample",DB: *(*"github.com/jinzhu/gorm.DB")(0xc0003a2b60),Auth: github.com/qor/admin.Auth nil,AssetFS: github.com/qor/assetfs.Interface(*github.com/qor/assetfs.AssetFileSystem) ...,SessionManager: github.com/qor/session.ManagerInterface(*github.com/qor/session/gorilla.Gorilla) ...,SettingsStorage: github.com/qor/admin.SettingsStorageInterface(github.com/qor/admin.settings) *(*"github.com/qor/admin.SettingsStorageInterface")(0xc000391078),I18n: github.com/qor/admin.I18n nil,Transformer: *(*"github.com/qor/admin.Transformer")(0xedcb30),},menus: []*github.com/qor/admin.Menu len: 0, cap: 0, nil,resources: []*github.com/qor/admin.Resource len: 0, cap: 0, nil,searchResources: []*github.com/qor/admin.Resource len: 0, cap: 0, nil,router: *github.com/qor/admin.Router {Prefix: "",routers: map[string][]*github.com/qor/admin.routeHandler [...],middlewares: []*github.com/qor/admin.Middleware len: 1, cap: 1, [*(*"github.com/qor/admin.Middleware")(0xc0003d8c00),],},funcMaps: html/template.FuncMap [],metaConfigorMaps: map[string]func(*github.com/qor/admin.Meta) ["single_edit": github.com/qor/admin.glob..func7,"date": github.com/qor/admin.glob..func1,"datetime": github.com/qor/admin.glob..func2,"string": github.com/qor/admin.glob..func3,"text": github.com/qor/admin.glob..func4,"select_one": github.com/qor/admin.glob..func5,"select_many": github.com/qor/admin.glob..func6,"collection_edit": github.com/qor/admin.glob..func8,"rich_editor": github.com/qor/admin.glob..func9,],}
func (admin *Admin) AddResource(value interface{}, config ...*Config) *Resource {res := admin.newResource(value, config...)admin.resources = append(admin.resources, res)res.configure()if !res.Config.Invisible {res.Action(&Action{Name: "Delete",Method: "DELETE",URL: func(record interface{}, context *Context) string {return context.URLFor(record, res)},Permission: res.Config.Permission,Modes: []string{"menu_item"},})menuName := res.Nameif !res.Config.Singleton {menuName = inflection.Plural(res.Name)}admin.AddMenu(&Menu{Name: menuName, IconName: res.Config.IconName, Permissioner: res, Priority: res.Config.Priority, Ancestors: res.Config.Menu, RelativePath: res.ToParam()})admin.RegisterResourceRouters(res, "create", "update", "read", "delete")}return res}
func (admin *Admin) newResource(value interface{}, config ...*Config) *Resource {var configuration *Configif len(config) > 0 {configuration = config[0]}if configuration == nil {configuration = &Config{}}/**github.com/qor/admin.Config {Name: "",IconName: "",Menu: []string len: 0, cap: 0, nil,Permission: *github.com/qor/roles.Permission nil,Themes: []github.com/qor/admin.ThemeInterface len: 0, cap: 0, nil,Priority: 0,Singleton: false,Invisible: false,PageCount: 0,}res := &Resource{Resource: resource.New(value),Config: configuration,admin: admin,}*/res.Permission = configuration.Permissionif configuration.Name != "" {res.Name = configuration.Name} else if namer, ok := value.(ResourceNamer); ok {res.Name = namer.ResourceName()}// Configure resource when initializingmodelType := utils.ModelType(res.Value)for i := 0; i < modelType.NumField(); i++ {if fieldStruct := modelType.Field(i); fieldStruct.Anonymous {/*(dlv) p fieldStructreflect.StructField {Name: "Model",PkgPath: "",Type: reflect.Type(*reflect.rtype) *{size: 64, ptrdata: 64, hash: 3737373484, tflag: tflagUncommon|tflagExtraStar|tflagNamed|tflagRegularMemory (15), align: 8, fieldAlign: 8, kind: 25, equal: runtime.memequal_varlen, gcdata: *200, str: 37822, ptrToThis: 185536},Tag: "",Offset: 0,Index: []int len: 1, cap: 1, [0],Anonymous: true,}*/if injector, ok := reflect.New(fieldStruct.Type).Interface().(resource.ConfigureResourceBeforeInitializeInterface); ok {injector.ConfigureQorResourceBeforeInitialize(res)}}}if injector, ok := res.Value.(resource.ConfigureResourceBeforeInitializeInterface); ok {injector.ConfigureQorResourceBeforeInitialize(res)}findOneHandler := res.FindOneHandlerres.FindOneHandler = func(result interface{}, metaValues *resource.MetaValues, context *qor.Context) error {if context.ResourceID == "" {context.ResourceID = res.GetPrimaryValue(context.Request)}return findOneHandler(result, metaValues, context)}res.UseTheme("slideout")return res}
func (admin *Admin) NewServeMux(prefix string) http.Handler {// Register default routes & middlewaresrouter := admin.routerrouter.Prefix = prefixadminController := &Controller{Admin: admin}router.Get("", adminController.Dashboard)router.Get("/!search", adminController.SearchCenter)browserUserAgentRegexp := regexp.MustCompile("Mozilla|Gecko|WebKit|MSIE|Opera")router.Use(&Middleware{Name: "csrf_check",Handler: func(context *Context, middleware *Middleware) {request := context.Requestif request.Method != "GET" {if browserUserAgentRegexp.MatchString(request.UserAgent()) {if referrer := request.Referer(); referrer != "" {if r, err := url.Parse(referrer); err == nil {if r.Host == request.Host {middleware.Next(context)return}}}context.Writer.Write([]byte("Could not authorize you because 'CSRF detected'"))return}}middleware.Next(context)},})router.Use(&Middleware{Name: "qor_handler",Handler: func(context *Context, middleware *Middleware) {context.Writer.Header().Set("Cache-control", "no-store")context.Writer.Header().Set("Pragma", "no-cache")if context.RouteHandler != nil {context.RouteHandler.Handle(context)return}http.NotFound(context.Writer, context.Request)},})return &serveMux{admin: admin}}
> github.com/qor/admin.(*serveMux).ServeHTTP() /root/go/pkg/mod/github.com/qor/admin@v1.2.0/route.go:212 (hits goroutine(8):1 total:1) (PC: 0xa6b3db)207: type serveMux struct {208: admin *Admin209: }210:211: // ServeHTTP dispatches the handler registered in the matched route=> 212: func (serveMux *serveMux) ServeHTTP(w http.ResponseWriter, req *http.Request) {213: var (214: admin = serveMux.admin215: RelativePath = "/" + strings.Trim(strings.TrimPrefix(req.URL.Path, admin.router.Prefix), "/")216: context = admin.NewContext(w, req)217: )(dlv) bt0 0x0000000000a6b3db in github.com/qor/admin.(*serveMux).ServeHTTPat /root/go/pkg/mod/github.com/qor/admin@v1.2.0/route.go:2121 0x00000000007cc2ab in net/http.(*ServeMux).ServeHTTPat /usr/lib/golang/src/net/http/server.go:24172 0x00000000007cdfab in net/http.serverHandler.ServeHTTPat /usr/lib/golang/src/net/http/server.go:28433 0x00000000007c83e5 in net/http.(*conn).serveat /usr/lib/golang/src/net/http/server.go:19254 0x0000000000477801 in runtime.goexitat /usr/lib/golang/src/runtime/asm_amd64.s:1374
> github.com/qor/admin.(*serveMux).ServeHTTP() /root/go/pkg/mod/github.com/qor/admin@v1.2.0/route.go:228 (PC: 0xa6b5ca)223: req.MultipartForm.RemoveAll()224: }225: }()226:227: // Set Request Method=> 228: if method := req.Form.Get("_method"); method != "" {229: req.Method = strings.ToUpper(method)230: }231:232: if regexp.MustCompile("^/assets/.*$").MatchString(RelativePath) && strings.ToUpper(req.Method) == "GET" {233: (&Controller{Admin: admin}).Asset(context)(dlv) p req*net/http.Request {Method: "GET",URL: *net/url.URL {Scheme: "",Opaque: "",User: *net/url.Userinfo nil,Host: "",Path: "/admin",RawPath: "",ForceQuery: false,RawQuery: "",Fragment: "",RawFragment: "",},Proto: "HTTP/1.1",ProtoMajor: 1,ProtoMinor: 1,Header: net/http.Header ["Connection": ["keep-alive",],"Upgrade-Insecure-Requests": ["1"],"User-Agent": ["Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHT...+50 more",],"Accept": ["text/html,application/xhtml+xml,application/xml;q=0.9,image/avif...+71 more",],"Accept-Encoding": ["gzip, deflate",],"Accept-Language": ["zh-CN,zh;q=0.9,en;q=0.8",],"Cookie": ["_session=MTY0MTIyMDI3NXxEdi1CQkFFQ180SUFBUkFCRUFBQUpQLUNBQUVHYzN...+101 more",],],Body: io.ReadCloser(net/http.noBody) {},GetBody: nil,ContentLength: 0,TransferEncoding: []string len: 0, cap: 0, nil,Close: false,Host: "175.24.244.132:9300",Form: net/url.Values [],PostForm: net/url.Values [],MultipartForm: *mime/multipart.Form nil,Trailer: net/http.Header nil,RemoteAddr: "117.136.87.70:28273",RequestURI: "/admin",TLS: *crypto/tls.ConnectionState nil,Cancel: <-chan struct {} {},Response: *net/http.Response nil,ctx: context.Context(*context.cancelCtx) *{Context: context.Context(*context.cancelCtx) ...,mu: (*sync.Mutex)(0xc0003d9010),done: chan struct {} {},children: map[context.canceler]struct {} nil,err: error nil,},}
(dlv) p req*net/http.Request {Method: "GET",URL: *net/url.URL {Scheme: "",Opaque: "",User: *net/url.Userinfo nil,Host: "",Path: "/admin",RawPath: "",ForceQuery: false,RawQuery: "",Fragment: "",RawFragment: "",},Proto: "HTTP/1.1",ProtoMajor: 1,ProtoMinor: 1,Header: net/http.Header ["Cache-Control": ["max-age=0",],"Upgrade-Insecure-Requests": ["1"],"Accept": ["text/html,application/xhtml+xml,application/xml;q=0.9,image/avif...+71 more",],"Accept-Encoding": ["gzip, deflate",],"Cookie": ["_session=MTY0MTMwNjYxOHxEdi1CQkFFQ180SUFBUkFCRUFBQUpQLUNBQUVHYzN...+101 more",],"Connection": ["keep-alive",],"User-Agent": ["Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHT...+50 more",],"Accept-Language": ["zh-CN,zh;q=0.9,en;q=0.8",],],Body: io.ReadCloser(net/http.noBody) {},GetBody: nil,ContentLength: 0,TransferEncoding: []string len: 0, cap: 0, nil,Close: false,Host: "175.24.244.132:9300",Form: net/url.Values nil,PostForm: net/url.Values nil,MultipartForm: *mime/multipart.Form nil,Trailer: net/http.Header nil,RemoteAddr: "117.136.87.70:29718",RequestURI: "/admin",TLS: *crypto/tls.ConnectionState nil,Cancel: <-chan struct {} {},Response: *net/http.Response nil,ctx: context.Context(*context.cancelCtx) *{Context: context.Context(*context.cancelCtx) ...,mu: (*sync.Mutex)(0xc0003d9010),done: chan struct {} {},children: map[context.canceler]struct {} nil,err: error nil,},}
