web

package
v9.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 15, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Overview

Package web provides HTTP-layer helpers shared by the admin web server.

It contains composable middleware and handlers for request metrics, reverse proxying, long-lived server-sent events streams, and prequery caching behavior. These helpers are framework-oriented utilities and keep business rules in adminapi/app packages.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CreateToken

func CreateToken(secret, uid, level string, exp time.Duration) (string, error)

func NewSingleHostReverseProxy

func NewSingleHostReverseProxy(prefix string, target *url.URL, rmAuth bool) *httputil.ReverseProxy

func ParseEqualMap

func ParseEqualMap(c echo.Context) map[string]string

func ParseFilterMap

func ParseFilterMap(c echo.Context) map[string]string

func ParseSortMap

func ParseSortMap(c echo.Context) map[string]string

func QueryDataResult

func QueryDataResult[T any](c echo.Context, tx *gorm.DB, prequery *PreQuery) ([]T, error)

func ReadImportCsvData

func ReadImportCsvData(src io.Reader) ([]map[string]interface{}, error)

func ReadImportExcelData

func ReadImportExcelData(src io.Reader, sheet string) ([]map[string]interface{}, error)

func ReadImportJsonData

func ReadImportJsonData(src io.Reader) ([]map[string]interface{}, error)

Types

type DateRange

type DateRange struct {
	Start string `json:"start"`
	End   string `json:"end"`
}

func (DateRange) ParseEnd

func (d DateRange) ParseEnd() (time.Time, error)

func (DateRange) ParseStart

func (d DateRange) ParseStart() (time.Time, error)

type JsonOptions

type JsonOptions struct {
	Id    string `json:"id"`
	Value string `json:"value"`
}

type Metrics

type Metrics struct {
	Icon  string
	Value interface{}
	Title string
}

func NewMetrics

func NewMetrics(icon string, value interface{}, title string) *Metrics

type PageResult

type PageResult struct {
	TotalCount int64       `json:"total_count,omitempty"`
	Pos        int64       `json:"pos"`
	Data       interface{} `json:"data"`
}

func QueryPageResult

func QueryPageResult[T any](c echo.Context, tx *gorm.DB, prequery *PreQuery) (*PageResult, error)

type ParamReader

type ParamReader struct {
	LastError error
	// contains filtered or unexported fields
}

ParamReader reads typed values from WebForm and records the first parse error.

func NewParamReader

func NewParamReader(c echo.Context) *ParamReader

func (*ParamReader) ReadInt

func (sr *ParamReader) ReadInt(ref *int, name string, defval int) *ParamReader

func (*ParamReader) ReadInt64

func (sr *ParamReader) ReadInt64(ref *int64, name string, defval int64) *ParamReader

func (*ParamReader) ReadRequiedString

func (sr *ParamReader) ReadRequiedString(ref *string, name string) *ParamReader

func (*ParamReader) ReadString

func (sr *ParamReader) ReadString(ref *string, name string) *ParamReader

func (*ParamReader) ReadStringWithDefault

func (sr *ParamReader) ReadStringWithDefault(ref *string, name string, defval string) *ParamReader

type PreQuery

type PreQuery struct {
	// contains filtered or unexported fields
}

PreQuery is a fluent query builder for constructing GORM queries from HTTP request parameters. It provides a chainable API for building complex database queries with:

  • Date range filtering
  • Field equality matching
  • Keyword search across multiple fields
  • Sorting and pagination
  • Custom parameter mapping

This is commonly used in REST API list endpoints to translate query parameters into SQL WHERE clauses and ORDER BY statements.

Example:

prequery := NewPreQuery(c).
    DefaultOrderBy("created_at DESC").
    DateRange("dateRange", "created_at", startTime, endTime).
    KeyFields("username", "email").
    EqualFields("status")

var users []User
query := prequery.Query(db.Model(&User{}))
query.Find(&users)

func NewPreQuery

func NewPreQuery(c echo.Context) *PreQuery

NewPreQuery creates a new PreQuery instance from an Echo context. This initializes the query builder with request parameters from the HTTP context.

Parameters:

  • c: Echo context containing query/form parameters

Returns:

  • *PreQuery: Chainable query builder instance

Example:

func ListUsers(c echo.Context) error {
    prequery := web.NewPreQuery(c)
    // Chain query methods...
}

func (*PreQuery) DateRange

func (p *PreQuery) DateRange(queryfd, timefd string, defaltStart time.Time, defaultEnd time.Time) *PreQuery

DateRange adds a date range filter to the query from a JSON-encoded query parameter. The query parameter should contain a DateRange JSON object with "start" and "end" fields.

Parameters:

  • queryfd: Name of query parameter containing JSON date range (e.g., "dateRange")
  • timefd: Database column name for date/time filtering (e.g., "created_at")
  • defaltStart: Default start time if not provided in request
  • defaultEnd: Default end time if not provided in request

Returns:

  • *PreQuery: Self for method chaining

Example:

// Request: ?dateRange={"start":"2024-01-01 00:00:00","end":"2024-12-31 23:59:59"}
prequery.DateRange("dateRange", "created_at", time.Now().AddDate(0, -1, 0), time.Now())

func (*PreQuery) DateRange2

func (p *PreQuery) DateRange2(startfd, endfd, timefd string, defaltStart time.Time, defaultEnd time.Time) *PreQuery

DateRange2 adds a date range filter using separate start/end query parameters. This is an alternative to DateRange when the client sends separate parameters instead of JSON.

Parameters:

  • startfd: Query parameter name for start date (e.g., "start_time")
  • endfd: Query parameter name for end date (e.g., "end_time")
  • timefd: Database column name for date/time filtering
  • defaltStart: Default start time if startfd is missing
  • defaultEnd: Default end time if endfd is missing

Returns:

  • *PreQuery: Self for method chaining

Example:

// Request: ?start_time=2024-01-01&end_time=2024-12-31
prequery.DateRange2("start_time", "end_time", "created_at", yesterday, now)

func (*PreQuery) DefaultOrderBy

func (p *PreQuery) DefaultOrderBy(fd string) *PreQuery

DefaultOrderBy sets the default sort order when no sort parameter is provided in the request. The sort field should be a valid database column name with optional direction.

Parameters:

  • fd: Default ORDER BY clause (e.g., "id DESC", "created_at ASC")

Returns:

  • *PreQuery: Self for method chaining

Example:

prequery.DefaultOrderBy("created_at DESC")

func (*PreQuery) EqualFields

func (p *PreQuery) EqualFields(fd ...string) *PreQuery

EqualFields specifies which filter parameters should use exact matching (=) instead of LIKE. By default, filter parameters use LIKE with wildcard matching.

Parameters:

  • fd: Field names that require exact equality matching

Returns:

  • *PreQuery: Self for method chaining

Example:

// status and user_id will use "=" while other fields use "LIKE"
prequery.EqualFields("status", "user_id")

func (*PreQuery) KeyFields

func (p *PreQuery) KeyFields(fd ...string) *PreQuery

KeyFields specifies which database columns should be searched when a "keyword" query parameter is present. The keyword will be matched against all specified fields using LIKE with OR logic.

Parameters:

  • fd: Database column names to search (e.g., "username", "email", "phone")

Returns:

  • *PreQuery: Self for method chaining

Example:

// Request: ?keyword=john
// SQL: WHERE username LIKE '%john%' OR email LIKE '%john%'
prequery.KeyFields("username", "email")

func (*PreQuery) Query

func (p *PreQuery) Query(query *gorm.DB) *gorm.DB

Query applies all configured filters to a GORM query and returns the modified query. This is the final step in the builder chain that constructs the actual SQL WHERE and ORDER BY clauses.

The method processes:

  1. Sorting from "sort" query parameter (or default sort if not provided)
  2. Date range filtering (if configured via DateRange/DateRange2)
  3. Exact match filters from "equal" query parameters
  4. Custom parameters from SetParam and QueryField
  5. Wildcard filters from "filter" query parameters
  6. Keyword search across KeyFields (if "keyword" parameter present)

Parameters:

  • query: Base GORM query to modify

Returns:

  • *gorm.DB: Modified query with WHERE and ORDER BY clauses applied

Example:

prequery := NewPreQuery(c).
    DefaultOrderBy("id DESC").
    KeyFields("username", "email")

var users []User
db := prequery.Query(app.GDB().Model(&User{}))
db.Find(&users)

func (*PreQuery) QueryField

func (p *PreQuery) QueryField(column, qfield string) *PreQuery

QueryField maps a specific query parameter to a database column for filtering. This allows custom parameter-to-column mapping beyond the automatic filtering.

Parameters:

  • column: Database column name (e.g., "user_id")
  • qfield: Query parameter name (e.g., "userId")

Returns:

  • *PreQuery: Self for method chaining

Example:

// Request: ?node_id=123
// SQL: WHERE nas_node_id = '123'
prequery.QueryField("nas_node_id", "node_id")

func (*PreQuery) SetParam

func (p *PreQuery) SetParam(key string, value interface{}) *PreQuery

SetParam manually sets a filter parameter that will be applied as an equality condition. This is useful for programmatically adding filters beyond HTTP request parameters.

Parameters:

  • key: Database column name
  • value: Value to match (will be used in WHERE key = value)

Returns:

  • *PreQuery: Self for method chaining

Example:

// Force filter by current user's node
prequery.SetParam("node_id", currentUser.NodeID)

type SSE

type SSE struct {
	EchoContext echo.Context
	context.Context
}

func NewSSE

func NewSSE(ectx echo.Context) *SSE

func (*SSE) Write

func (sse *SSE) Write(data []byte) (n int, err error)

func (*SSE) WriteEvent

func (sse *SSE) WriteEvent(event string, data []byte) (err error)

func (*SSE) WriteExec

func (sse *SSE) WriteExec(cmd *exec.Cmd) error

func (*SSE) WriteJSON

func (sse *SSE) WriteJSON(data interface{}) (err error)

func (*SSE) WriteMessage

func (sse *SSE) WriteMessage(msg SSEMessage) (err error)

func (*SSE) WriteText

func (sse *SSE) WriteText(msg string) (err error)

type SSEMessage

type SSEMessage struct {
	Id     string      `json:"id"`
	Action string      `json:"action"`
	Error  string      `json:"error,omitempty"`
	Data   interface{} `json:"data,omitempty"`
}

type WebForm

type WebForm struct {
	FormItem interface{}
	Posts    url.Values        `json:"-" form:"-" query:"-"`
	Gets     url.Values        `json:"-" form:"-" query:"-"`
	Params   map[string]string `json:"-" form:"-" query:"-"`
}

WebForm stores merged path/query/form parameters and helper accessors.

func EmptyWebForm

func EmptyWebForm() *WebForm

func NewWebForm

func NewWebForm(c echo.Context) *WebForm

func (*WebForm) GetDateRange

func (f *WebForm) GetDateRange(name string) (DateRange, error)

func (*WebForm) GetInt64Val

func (f *WebForm) GetInt64Val(name string, defval int64) int64

func (*WebForm) GetIntVal

func (f *WebForm) GetIntVal(name string, defval int) int

func (*WebForm) GetMustVal

func (f *WebForm) GetMustVal(name string) (string, error)

func (*WebForm) GetVal

func (f *WebForm) GetVal(name string) string

func (*WebForm) GetVal2

func (f *WebForm) GetVal2(name string, defval string) string

func (*WebForm) Param

func (f *WebForm) Param(name string) string

func (*WebForm) Param2

func (f *WebForm) Param2(name string, defval string) string

func (*WebForm) ParseTimeDesc

func (f *WebForm) ParseTimeDesc(timestr string, defval string) string

ParseTimeDesc parses a time description now-1hour indicates the past hour now-1min indicates the past minute now-1day indicates the past day

func (*WebForm) Set

func (f *WebForm) Set(name string, value string)

type WebRestResult

type WebRestResult struct {
	Code    int         `json:"code"`
	Msgtype string      `json:"msgtype"`
	Msg     string      `json:"msg"`
	Data    interface{} `json:"data"`
}

func RestError

func RestError(msg string) *WebRestResult

func RestResult

func RestResult(data interface{}) *WebRestResult

func RestSucc

func RestSucc(msg string) *WebRestResult

type WebixTableColumn

type WebixTableColumn struct {
	Id         string      `json:"id,omitempty"`
	Header     interface{} `json:"header,omitempty"`
	Headermenu interface{} `json:"headermenu,omitempty"`
	Editor     string      `json:"editor,omitempty"`
	Options    interface{} `json:"options,omitempty"`
	Adjust     interface{} `json:"adjust,omitempty"`
	Hidden     interface{} `json:"hidden,omitempty"`
	Sort       string      `json:"sort,omitempty"`
	Fillspace  interface{} `json:"fillspace,omitempty"`
	Css        string      `json:"css,omitempty"`
	Template   string      `json:"template,omitempty"`
	Width      int         `json:"width,omitempty"`
	Height     int         `json:"height,omitempty"`
}

WebixTableColumn defines a column descriptor for Webix table configuration.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL