结构体:

    qor - 图1

    1. package main
    2. import (
    3. "fmt"
    4. "net/http"
    5. "github.com/qor/admin"
    6. "github.com/jinzhu/gorm"
    7. _ "github.com/jinzhu/gorm/dialects/mysql"
    8. //windows需要下载 http://tdm-gcc.tdragon.net/download
    9. )
    10. // 用户
    11. type User struct {
    12. gorm.Model
    13. Name string
    14. }
    15. // 产品
    16. type Product struct {
    17. gorm.Model
    18. Name string
    19. Description string
    20. }
    21. /*自定义结构可继承接口 重命名resource.Name
    22. type ResourceNamer interface {
    23. ResourceName() string
    24. }
    25. */
    26. func main() {
    27. // 注册数据库,可以是sqlite3 也可以是 mysql 换下驱动就可以了。
    28. mysql_url := "root:mariadb@tcp(175.24.244.132:3306)/qor_test?charset=utf8&parseTime=True&loc=Local"
    29. DB, _ := gorm.Open("mysql", mysql_url)
    30. DB.AutoMigrate(&User{}, &Product{}) //自动创建表。
    31. // 初始化admin 还有其他的,比如API
    32. Admin := admin.New(&admin.AdminConfig{DB: DB})
    33. // 创建admin后台对象资源。
    34. Admin.AddResource(&User{})
    35. Admin.AddResource(&Product{})
    36. // 启动服务
    37. mux := http.NewServeMux()
    38. Admin.MountTo("/admin", mux)
    39. fmt.Println("Listening on: 9000")
    40. http.ListenAndServe(":9000", mux)
    41. }
    1. func New(config interface{}) *Admin {
    2. admin := Admin{
    3. funcMaps: make(template.FuncMap),
    4. router: newRouter(),
    5. metaConfigorMaps: defaultMetaConfigorMaps,
    6. }
    7. if c, ok := config.(*qor.Config); ok {
    8. admin.AdminConfig = &AdminConfig{DB: c.DB}
    9. } else if c, ok := config.(*AdminConfig); ok {
    10. admin.AdminConfig = c
    11. } else {
    12. admin.AdminConfig = &AdminConfig{}
    13. }
    14. if admin.SessionManager == nil {
    15. admin.SessionManager = manager.SessionManager
    16. }
    17. if admin.Transformer == nil {
    18. admin.Transformer = DefaultTransformer
    19. }
    20. if admin.AssetFS == nil {
    21. admin.AssetFS = assetfs.AssetFS().NameSpace("admin")
    22. }
    23. if admin.SettingsStorage == nil {
    24. admin.SettingsStorage = newSettings(admin.AdminConfig.DB)
    25. }
    26. admin.SetAssetFS(admin.AssetFS)
    27. if admin.AdminConfig.DB != nil {
    28. admin.AdminConfig.DB.AutoMigrate(&QorAdminSetting{})
    29. }
    30. admin.registerCompositePrimaryKeyCallback()
    31. return &admin
    32. }

    debug

    1. *github.com/qor/admin.Admin {
    2. AdminConfig: *github.com/qor/admin.AdminConfig {
    3. SiteName: "QExample",
    4. DB: *(*"github.com/jinzhu/gorm.DB")(0xc0003a2b60),
    5. Auth: github.com/qor/admin.Auth nil,
    6. AssetFS: github.com/qor/assetfs.Interface(*github.com/qor/assetfs.AssetFileSystem) ...,
    7. SessionManager: github.com/qor/session.ManagerInterface(*github.com/qor/session/gorilla.Gorilla) ...,
    8. SettingsStorage: github.com/qor/admin.SettingsStorageInterface(github.com/qor/admin.settings) *(*"github.com/qor/admin.SettingsStorageInterface")(0xc000391078),
    9. I18n: github.com/qor/admin.I18n nil,
    10. Transformer: *(*"github.com/qor/admin.Transformer")(0xedcb30),},
    11. menus: []*github.com/qor/admin.Menu len: 0, cap: 0, nil,
    12. resources: []*github.com/qor/admin.Resource len: 0, cap: 0, nil,
    13. searchResources: []*github.com/qor/admin.Resource len: 0, cap: 0, nil,
    14. router: *github.com/qor/admin.Router {
    15. Prefix: "",
    16. routers: map[string][]*github.com/qor/admin.routeHandler [...],
    17. middlewares: []*github.com/qor/admin.Middleware len: 1, cap: 1, [
    18. *(*"github.com/qor/admin.Middleware")(0xc0003d8c00),
    19. ],},
    20. funcMaps: html/template.FuncMap [],
    21. metaConfigorMaps: map[string]func(*github.com/qor/admin.Meta) [
    22. "single_edit": github.com/qor/admin.glob..func7,
    23. "date": github.com/qor/admin.glob..func1,
    24. "datetime": github.com/qor/admin.glob..func2,
    25. "string": github.com/qor/admin.glob..func3,
    26. "text": github.com/qor/admin.glob..func4,
    27. "select_one": github.com/qor/admin.glob..func5,
    28. "select_many": github.com/qor/admin.glob..func6,
    29. "collection_edit": github.com/qor/admin.glob..func8,
    30. "rich_editor": github.com/qor/admin.glob..func9,
    31. ],}
    1. func (admin *Admin) AddResource(value interface{}, config ...*Config) *Resource {
    2. res := admin.newResource(value, config...)
    3. admin.resources = append(admin.resources, res)
    4. res.configure()
    5. if !res.Config.Invisible {
    6. res.Action(&Action{
    7. Name: "Delete",
    8. Method: "DELETE",
    9. URL: func(record interface{}, context *Context) string {
    10. return context.URLFor(record, res)
    11. },
    12. Permission: res.Config.Permission,
    13. Modes: []string{"menu_item"},
    14. })
    15. menuName := res.Name
    16. if !res.Config.Singleton {
    17. menuName = inflection.Plural(res.Name)
    18. }
    19. admin.AddMenu(&Menu{Name: menuName, IconName: res.Config.IconName, Permissioner: res, Priority: res.Config.Priority, Ancestors: res.Config.Menu, RelativePath: res.ToParam()})
    20. admin.RegisterResourceRouters(res, "create", "update", "read", "delete")
    21. }
    22. return res
    23. }
    1. func (admin *Admin) newResource(value interface{}, config ...*Config) *Resource {
    2. var configuration *Config
    3. if len(config) > 0 {
    4. configuration = config[0]
    5. }
    6. if configuration == nil {
    7. configuration = &Config{}
    8. }
    9. /*
    10. *github.com/qor/admin.Config {
    11. Name: "",
    12. IconName: "",
    13. Menu: []string len: 0, cap: 0, nil,
    14. Permission: *github.com/qor/roles.Permission nil,
    15. Themes: []github.com/qor/admin.ThemeInterface len: 0, cap: 0, nil,
    16. Priority: 0,
    17. Singleton: false,
    18. Invisible: false,
    19. PageCount: 0,}
    20. res := &Resource{
    21. Resource: resource.New(value),
    22. Config: configuration,
    23. admin: admin,
    24. }
    25. */
    26. res.Permission = configuration.Permission
    27. if configuration.Name != "" {
    28. res.Name = configuration.Name
    29. } else if namer, ok := value.(ResourceNamer); ok {
    30. res.Name = namer.ResourceName()
    31. }
    32. // Configure resource when initializing
    33. modelType := utils.ModelType(res.Value)
    34. for i := 0; i < modelType.NumField(); i++ {
    35. if fieldStruct := modelType.Field(i); fieldStruct.Anonymous {
    36. /*(dlv) p fieldStruct
    37. reflect.StructField {
    38. Name: "Model",
    39. PkgPath: "",
    40. 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},
    41. Tag: "",
    42. Offset: 0,
    43. Index: []int len: 1, cap: 1, [0],
    44. Anonymous: true,}*/
    45. if injector, ok := reflect.New(fieldStruct.Type).Interface().(resource.ConfigureResourceBeforeInitializeInterface); ok {
    46. injector.ConfigureQorResourceBeforeInitialize(res)
    47. }
    48. }
    49. }
    50. if injector, ok := res.Value.(resource.ConfigureResourceBeforeInitializeInterface); ok {
    51. injector.ConfigureQorResourceBeforeInitialize(res)
    52. }
    53. findOneHandler := res.FindOneHandler
    54. res.FindOneHandler = func(result interface{}, metaValues *resource.MetaValues, context *qor.Context) error {
    55. if context.ResourceID == "" {
    56. context.ResourceID = res.GetPrimaryValue(context.Request)
    57. }
    58. return findOneHandler(result, metaValues, context)
    59. }
    60. res.UseTheme("slideout")
    61. return res
    62. }
    1. func (admin *Admin) NewServeMux(prefix string) http.Handler {
    2. // Register default routes & middlewares
    3. router := admin.router
    4. router.Prefix = prefix
    5. adminController := &Controller{Admin: admin}
    6. router.Get("", adminController.Dashboard)
    7. router.Get("/!search", adminController.SearchCenter)
    8. browserUserAgentRegexp := regexp.MustCompile("Mozilla|Gecko|WebKit|MSIE|Opera")
    9. router.Use(&Middleware{
    10. Name: "csrf_check",
    11. Handler: func(context *Context, middleware *Middleware) {
    12. request := context.Request
    13. if request.Method != "GET" {
    14. if browserUserAgentRegexp.MatchString(request.UserAgent()) {
    15. if referrer := request.Referer(); referrer != "" {
    16. if r, err := url.Parse(referrer); err == nil {
    17. if r.Host == request.Host {
    18. middleware.Next(context)
    19. return
    20. }
    21. }
    22. }
    23. context.Writer.Write([]byte("Could not authorize you because 'CSRF detected'"))
    24. return
    25. }
    26. }
    27. middleware.Next(context)
    28. },
    29. })
    30. router.Use(&Middleware{
    31. Name: "qor_handler",
    32. Handler: func(context *Context, middleware *Middleware) {
    33. context.Writer.Header().Set("Cache-control", "no-store")
    34. context.Writer.Header().Set("Pragma", "no-cache")
    35. if context.RouteHandler != nil {
    36. context.RouteHandler.Handle(context)
    37. return
    38. }
    39. http.NotFound(context.Writer, context.Request)
    40. },
    41. })
    42. return &serveMux{admin: admin}
    43. }
    1. > 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)
    2. 207: type serveMux struct {
    3. 208: admin *Admin
    4. 209: }
    5. 210:
    6. 211: // ServeHTTP dispatches the handler registered in the matched route
    7. => 212: func (serveMux *serveMux) ServeHTTP(w http.ResponseWriter, req *http.Request) {
    8. 213: var (
    9. 214: admin = serveMux.admin
    10. 215: RelativePath = "/" + strings.Trim(strings.TrimPrefix(req.URL.Path, admin.router.Prefix), "/")
    11. 216: context = admin.NewContext(w, req)
    12. 217: )
    13. (dlv) bt
    14. 0 0x0000000000a6b3db in github.com/qor/admin.(*serveMux).ServeHTTP
    15. at /root/go/pkg/mod/github.com/qor/admin@v1.2.0/route.go:212
    16. 1 0x00000000007cc2ab in net/http.(*ServeMux).ServeHTTP
    17. at /usr/lib/golang/src/net/http/server.go:2417
    18. 2 0x00000000007cdfab in net/http.serverHandler.ServeHTTP
    19. at /usr/lib/golang/src/net/http/server.go:2843
    20. 3 0x00000000007c83e5 in net/http.(*conn).serve
    21. at /usr/lib/golang/src/net/http/server.go:1925
    22. 4 0x0000000000477801 in runtime.goexit
    23. at /usr/lib/golang/src/runtime/asm_amd64.s:1374
    1. > github.com/qor/admin.(*serveMux).ServeHTTP() /root/go/pkg/mod/github.com/qor/admin@v1.2.0/route.go:228 (PC: 0xa6b5ca)
    2. 223: req.MultipartForm.RemoveAll()
    3. 224: }
    4. 225: }()
    5. 226:
    6. 227: // Set Request Method
    7. => 228: if method := req.Form.Get("_method"); method != "" {
    8. 229: req.Method = strings.ToUpper(method)
    9. 230: }
    10. 231:
    11. 232: if regexp.MustCompile("^/assets/.*$").MatchString(RelativePath) && strings.ToUpper(req.Method) == "GET" {
    12. 233: (&Controller{Admin: admin}).Asset(context)
    13. (dlv) p req
    14. *net/http.Request {
    15. Method: "GET",
    16. URL: *net/url.URL {
    17. Scheme: "",
    18. Opaque: "",
    19. User: *net/url.Userinfo nil,
    20. Host: "",
    21. Path: "/admin",
    22. RawPath: "",
    23. ForceQuery: false,
    24. RawQuery: "",
    25. Fragment: "",
    26. RawFragment: "",},
    27. Proto: "HTTP/1.1",
    28. ProtoMajor: 1,
    29. ProtoMinor: 1,
    30. Header: net/http.Header [
    31. "Connection": [
    32. "keep-alive",
    33. ],
    34. "Upgrade-Insecure-Requests": ["1"],
    35. "User-Agent": [
    36. "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHT...+50 more",
    37. ],
    38. "Accept": [
    39. "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif...+71 more",
    40. ],
    41. "Accept-Encoding": [
    42. "gzip, deflate",
    43. ],
    44. "Accept-Language": [
    45. "zh-CN,zh;q=0.9,en;q=0.8",
    46. ],
    47. "Cookie": [
    48. "_session=MTY0MTIyMDI3NXxEdi1CQkFFQ180SUFBUkFCRUFBQUpQLUNBQUVHYzN...+101 more",
    49. ],
    50. ],
    51. Body: io.ReadCloser(net/http.noBody) {},
    52. GetBody: nil,
    53. ContentLength: 0,
    54. TransferEncoding: []string len: 0, cap: 0, nil,
    55. Close: false,
    56. Host: "175.24.244.132:9300",
    57. Form: net/url.Values [],
    58. PostForm: net/url.Values [],
    59. MultipartForm: *mime/multipart.Form nil,
    60. Trailer: net/http.Header nil,
    61. RemoteAddr: "117.136.87.70:28273",
    62. RequestURI: "/admin",
    63. TLS: *crypto/tls.ConnectionState nil,
    64. Cancel: <-chan struct {} {},
    65. Response: *net/http.Response nil,
    66. ctx: context.Context(*context.cancelCtx) *{
    67. Context: context.Context(*context.cancelCtx) ...,
    68. mu: (*sync.Mutex)(0xc0003d9010),
    69. done: chan struct {} {},
    70. children: map[context.canceler]struct {} nil,
    71. err: error nil,},}
    1. (dlv) p req
    2. *net/http.Request {
    3. Method: "GET",
    4. URL: *net/url.URL {
    5. Scheme: "",
    6. Opaque: "",
    7. User: *net/url.Userinfo nil,
    8. Host: "",
    9. Path: "/admin",
    10. RawPath: "",
    11. ForceQuery: false,
    12. RawQuery: "",
    13. Fragment: "",
    14. RawFragment: "",},
    15. Proto: "HTTP/1.1",
    16. ProtoMajor: 1,
    17. ProtoMinor: 1,
    18. Header: net/http.Header [
    19. "Cache-Control": [
    20. "max-age=0",
    21. ],
    22. "Upgrade-Insecure-Requests": ["1"],
    23. "Accept": [
    24. "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif...+71 more",
    25. ],
    26. "Accept-Encoding": [
    27. "gzip, deflate",
    28. ],
    29. "Cookie": [
    30. "_session=MTY0MTMwNjYxOHxEdi1CQkFFQ180SUFBUkFCRUFBQUpQLUNBQUVHYzN...+101 more",
    31. ],
    32. "Connection": [
    33. "keep-alive",
    34. ],
    35. "User-Agent": [
    36. "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHT...+50 more",
    37. ],
    38. "Accept-Language": [
    39. "zh-CN,zh;q=0.9,en;q=0.8",
    40. ],
    41. ],
    42. Body: io.ReadCloser(net/http.noBody) {},
    43. GetBody: nil,
    44. ContentLength: 0,
    45. TransferEncoding: []string len: 0, cap: 0, nil,
    46. Close: false,
    47. Host: "175.24.244.132:9300",
    48. Form: net/url.Values nil,
    49. PostForm: net/url.Values nil,
    50. MultipartForm: *mime/multipart.Form nil,
    51. Trailer: net/http.Header nil,
    52. RemoteAddr: "117.136.87.70:29718",
    53. RequestURI: "/admin",
    54. TLS: *crypto/tls.ConnectionState nil,
    55. Cancel: <-chan struct {} {},
    56. Response: *net/http.Response nil,
    57. ctx: context.Context(*context.cancelCtx) *{
    58. Context: context.Context(*context.cancelCtx) ...,
    59. mu: (*sync.Mutex)(0xc0003d9010),
    60. done: chan struct {} {},
    61. children: map[context.canceler]struct {} nil,
    62. err: error nil,},}