-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathintegrator.go
More file actions
75 lines (65 loc) · 2.24 KB
/
integrator.go
File metadata and controls
75 lines (65 loc) · 2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package adminecho
import (
"fmt"
"github.com/go-advanced-admin/admin"
"github.com/labstack/echo/v4"
"mime"
"net/http"
"path/filepath"
)
// Integrator struct wraps an Echo group to handle routes and assets for the admin panel
type Integrator struct {
group *echo.Group
}
// NewIntegrator creates a new Integrator instance for the given Echo group
func NewIntegrator(g *echo.Group) *Integrator {
return &Integrator{group: g}
}
// HandleRoute adds a route to the Echo group and uses the admin.HandlerFunc for processing requests
func (i *Integrator) HandleRoute(method, path string, handler admin.HandlerFunc) {
i.group.Add(method, path, func(c echo.Context) error {
code, body := handler(c)
if code == http.StatusFound || code == http.StatusMovedPermanently || code == http.StatusSeeOther {
return c.Redirect(int(code), body)
}
return c.HTML(int(code), body)
})
}
// ServeAssets serves static assets by using the provided admin.TemplateRenderer interface
func (i *Integrator) ServeAssets(prefix string, renderer admin.TemplateRenderer) {
i.group.GET(fmt.Sprintf("/%s/*", prefix), func(c echo.Context) error {
fileName := c.Param("*")
fileData, err := renderer.GetAsset(fileName)
if err != nil {
return c.NoContent(http.StatusNotFound)
}
contentType := mime.TypeByExtension(filepath.Ext(fileName))
if contentType == "" {
contentType = "application/octet-stream"
}
return c.Blob(http.StatusOK, contentType, fileData)
})
}
// GetQueryParam extracts a query parameter from the context
func (i *Integrator) GetQueryParam(ctx interface{}, name string) string {
ec := ctx.(echo.Context)
return ec.QueryParam(name)
}
// GetPathParam extracts a path parameter from the context
func (i *Integrator) GetPathParam(ctx interface{}, name string) string {
ec := ctx.(echo.Context)
return ec.Param(name)
}
// GetRequestMethod retrieves the HTTP request method from the context
func (i *Integrator) GetRequestMethod(ctx interface{}) string {
ec := ctx.(echo.Context)
return ec.Request().Method
}
// GetFormData retrieves form data from the request context
func (i *Integrator) GetFormData(ctx interface{}) map[string][]string {
ec := ctx.(echo.Context)
if err := ec.Request().ParseForm(); err != nil {
return nil
}
return ec.Request().Form
}