web

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: May 15, 2026 License: MIT Imports: 17 Imported by: 0

Documentation

Overview

Package web is the Laravel-style HTTP framework for lagodev.

Bu paket Gin/Fiber'ga muqobil sodda, framework-mustaqil API beradi. Asosiy tushunchalar:

  • web.App — ilovaning tepa darajadagi konteyner (Router + Server + DB)
  • web.Context — har bir so'rovga moslangan helper'lar (JSON, Bind, Param)
  • web.Router — Laravel-uslubidagi marshrutlash (Get/Post/Resource/Group)
  • web.ResourceController — RESTful 5 metodli interfeys

Minimal misol:

app := web.New()
app.Get("/", func(c *web.Context) { c.String(200, "hi") })
app.Resource("posts", &PostController{})
app.Run(":8080")

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type App

type App struct {
	*Router // Top-level marshrutlash uchun embedded
	// contains filtered or unexported fields
}

App — ilovaning tepa darajadagi konteyner. Marshrutlar, ulanish, sozlamalar va HTTP server'ni birgalikda saqlaydi. Foydalanuvchi faqat main.go'da `web.New(...).Run()` chaqiradi.

func New

func New(opts ...Option) *App

New — yangi App yaratadi va kerakli o'rta dasturlarni standart qilib qo'shadi (Logger + Recovery). Disable qilish uchun Reset() chaqiring.

func (*App) DB

func (a *App) DB() *database.Connection

DB — biriktirilgan database.Connection'ni qaytaradi (yo'q bo'lsa nil).

func (*App) MustRun

func (a *App) MustRun(addr ...string)

MustRun — Run() qaytargan xato bo'lsa fatal log bilan to'xtaydi. Asosiy main() uchun qulay.

func (*App) Run

func (a *App) Run(addr ...string) error

Run — HTTP serverni ishga tushiradi va Ctrl+C kelguncha bloklanadi. Graceful shutdown signali kelganda joriy so'rovlar tamomlanguncha kutadi.

type Context

type Context struct {
	// Writer — yozish uchun standart http.ResponseWriter.
	Writer http.ResponseWriter
	// Request — kelgan HTTP so'rov.
	Request *http.Request
	// DB — agar App.WithDatabase orqali biriktirilgan bo'lsa, ulanish.
	// Hech qachon nil bo'lmasligi shart emas; nil bo'lganda foydalanuvchi
	// o'zi tekshiradi.
	DB *database.Connection
	// contains filtered or unexported fields
}

Context bitta HTTP so'rovni ifoda etadi. U handler'lar va middleware'lar orasidan o'tadi va so'rov/javob ustida ishlash uchun helper'lar beradi.

func (*Context) BadRequest

func (c *Context) BadRequest(msg string)

BadRequest 400 + JSON xato.

func (*Context) Bind

func (c *Context) Bind(dst any) error

Bind so'rov body'sini JSON sifatida dst'ga decode qiladi. Xato bo'lsa avtomatik 400 Bad Request qaytaradi va sentinel xatoni qaytaradi.

func (*Context) Created added in v0.8.0

func (c *Context) Created(v any) any

Created — Store handler uchun qulay yordamchi. 201 statusi'ni belgilab foydalanuvchi return value, nil yozsa, framework JSON'ga aylantiradi:

return ctx.Created(post), nil

func (*Context) Ctx

func (c *Context) Ctx() context.Context

Ctx so'rovning context.Context'ini qaytaradi. DB chaqiruvlariga uzating:

user, err := orm.Query[User](c.DB).Find(c.Ctx(), id)

func (*Context) Error

func (c *Context) Error(err error) bool

Error err nil emas bo'lsa, mos status kodi bilan JSON javob qaytaradi. orm.ErrNotFound uchun 404, qolganlar uchun 500. Foydalanish:

if c.Error(err) { return }

func (*Context) Forbidden

func (c *Context) Forbidden(msg string)

Forbidden 403 + JSON xato.

func (*Context) Get

func (c *Context) Get(key string) (any, bool)

Get saqlangan qiymatni oladi.

func (*Context) InternalError

func (c *Context) InternalError(err error)

InternalError 500 + JSON xato.

func (*Context) JSON

func (c *Context) JSON(code int, v any)

JSON v'ni JSON sifatida code statusi bilan yuboradi.

func (*Context) MustBind

func (c *Context) MustBind(dst any) bool

MustBind Bind bilan bir xil lekin xato bo'lsa true qaytaradi. Foydalanish: if !c.MustBind(&payload) { return }

func (*Context) NoContent

func (c *Context) NoContent()

NoContent 204 javobi (body yo'q).

func (*Context) NotFound

func (c *Context) NotFound(msg string)

NotFound 404 + JSON xato.

func (*Context) Param

func (c *Context) Param(name string) string

Param yo'l parametri qiymatini qaytaradi (masalan "/posts/{id}" → "id"). Yo'qol bo'lsa, bo'sh qator.

func (*Context) ParamInt

func (c *Context) ParamInt(name string) int

ParamInt yo'l parametri'ni int qiymat sifatida qaytaradi.

func (*Context) ParamUint

func (c *Context) ParamUint(name string) uint64

ParamUint yo'l parametri'ni uint64 ko'rinishida qaytaradi. Xato yoki bo'sh bo'lsa 0 qaytadi.

func (*Context) Query

func (c *Context) Query(name string) string

Query URL-dan so'rov stringini oladi (?key=value).

func (*Context) QueryDefault

func (c *Context) QueryDefault(name, fallback string) string

QueryDefault Query bilan bir xil, lekin bo'sh bo'lsa fallback qaytaradi.

func (*Context) QueryInt

func (c *Context) QueryInt(name string, fallback int) int

QueryInt URL parametrini int sifatida o'qiydi. Xato bo'lsa fallback.

func (*Context) Set

func (c *Context) Set(key string, value any)

Set context ichida key/value saqlaydi (masalan, authenticated user).

func (*Context) Status

func (c *Context) Status(code int)

Status faqat status kodini yozadi, body yubormaydi.

func (*Context) String

func (c *Context) String(code int, body string)

String matn javobi.

func (*Context) Unauthorized

func (c *Context) Unauthorized(msg string)

Unauthorized 401 + JSON xato.

type Handler

type Handler func(c *Context) (any, error)

Handler — har bir route metodining imzosi.

Laravel uslubida ikki qiymat qaytaradi:

  • any — JSON sifatida javob beriladi (nil bo'lsa, 204 No Content)
  • error — nil emas bo'lsa, avtomat xato javobi (orm.ErrNotFound → 404, qolganlari → 500). c.Status(N) chaqirib ham qo'shimcha holat kodini majburlash mumkin.

type Middleware

type Middleware func(next Handler) Handler

Middleware — Handler'ni boshqa Handler bilan o'rab oladigan funksiya. Birinchi ro'yxatga olingan middleware tashqaridagisi (so'rov birinchi uning ichidan o'tadi).

func Auth

func Auth() Middleware

Auth — placeholder Bearer-token avtorizatsiya middleware. Real ilovada JWT yoki session asosida tekshiruv qo'shasiz; bu skelet 401 qaytaradi agar `Authorization: Bearer ...` sarlavhasi yo'q bo'lsa.

func CORS

func CORS(allowedOrigins ...string) Middleware

CORS — sodda CORS middleware. Origin'ni allowedOrigins ro'yxati bilan taqqoslaydi (yoki "*" — har qanday).

func Logger

func Logger(l *log.Logger) Middleware

Logger — har bir so'rov uchun method, path, status kodi va davomiyligini log'ga yozadigan standart middleware. App.New() avtomat qo'shadi.

func Recovery

func Recovery(l *log.Logger) Middleware

Recovery — panic'ni tutib, JSON 500 javobini qaytaradigan middleware. Stack trace stderrga yoziladi. App.New() avtomat qo'shadi.

type Option

type Option func(*App)

Option — funksional sozlash usuli.

func WithAddr

func WithAddr(addr string) Option

WithAddr — server tinglovchi manzili (default ":8080").

func WithDatabase

func WithDatabase(conn *database.Connection) Option

WithDatabase — ochiq *database.Connection'ni ilovaga biriktiradi. Handler'lardan `c.DB` orqali foydalanish mumkin.

func WithManager

func WithManager(mgr *database.Manager) Option

WithManager — *database.Manager'ni biriktiradi. Run() chiqqach Close() chaqiriladi.

func WithMigrations

func WithMigrations(reg *migrations.Registry) Option

WithMigrations — Run() vaqtida migratsiyalarni avtomat qo'llashni yoqadi. Registry nil bo'lsa, package-default ishlatiladi.

func WithShutdownTimeout

func WithShutdownTimeout(d time.Duration) Option

WithShutdownTimeout — graceful shutdown vaqti (default 10s).

type ResourceController

type ResourceController interface {
	Index(c *Context) (any, error)
	Show(c *Context) (any, error)
	Store(c *Context) (any, error)
	Update(c *Context) (any, error)
	Destroy(c *Context) (any, error)
}

ResourceController — Resource() bilan ishlatish uchun interfeys. 5 ta RESTful metod (any, error) qaytaradi — Laravel uslubida.

type Route

type Route struct {
	Method  string
	Path    string
	Handler Handler
}

Route — bitta ro'yxatdan o'tgan marshrut.

type Router

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

Router — marshrut, group va middleware'larni e'lon qilish vositasi.

func (*Router) APIResource

func (r *Router) APIResource(name string, ctrl ResourceController)

APIResource — Resource bilan bir xil; nom Laravel konventsiyasi uchun.

func (*Router) Any

func (r *Router) Any(path string, h Handler)

Any — barcha standart HTTP fe'llari uchun bir xil handler.

func (*Router) Delete

func (r *Router) Delete(path string, h Handler)

func (*Router) Get

func (r *Router) Get(path string, h Handler)

HTTP verb shortcutlar — har biri prefiks va middleware bilan to'liq route ro'yxatga oladi.

func (*Router) Group

func (r *Router) Group(prefix string, fn func(g *Router))

Group — yangi prefiks va o'rta dasturlar to'plamiga ega bola router. Misol: app.Group("/api/v1", func(g *web.Router) { g.Resource("posts", ...) })

func (*Router) Head

func (r *Router) Head(path string, h Handler)

func (*Router) Options

func (r *Router) Options(path string, h Handler)

func (*Router) Patch

func (r *Router) Patch(path string, h Handler)

func (*Router) Post

func (r *Router) Post(path string, h Handler)

func (*Router) Put

func (r *Router) Put(path string, h Handler)

func (*Router) Resource

func (r *Router) Resource(name string, ctrl ResourceController)

Resource — RESTful 5 ta marshrutni avtomat e'lon qiladi.

GET    /posts            → Index
GET    /posts/{id}       → Show
POST   /posts            → Store
PUT    /posts/{id}       → Update
PATCH  /posts/{id}       → Update
DELETE /posts/{id}       → Destroy

`name` — ko'plik (`posts`, `users`).

func (*Router) Routes

func (r *Router) Routes() []Route

Routes — barcha ro'yxatga olingan marshrutlarning snapshot'i.

func (*Router) Use

func (r *Router) Use(mw ...Middleware)

Use — har bir keyingi marshrutga qo'llaniladigan middleware.

Jump to

Keyboard shortcuts

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