hime

package module
v0.0.0-...-9d4d9a5 Latest Latest
Warning

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

Go to latest
Published: Feb 24, 2025 License: MIT Imports: 37 Imported by: 0

README

Hime

codecov Go Report Card GoDoc

Hime is a Go Web Framework.

See Wiki for guide more information.

Why Framework

I ❤️ net/http but... there are many duplicated code when working on multiple projects, plus no standard. Framework creates a standard for developers.

Why Another Framework

There is many Go frameworks out there. But I want a framework that works with any net/http compatible libraries seamlessly.

For example, you can choose any router, any middlewares, or handlers that work with standard library.

That why hime won't ship with any handler include router 🙈

License

MIT

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrAppNotFound = errors.New("hime: app not found")
)

Errors

Functions

func Compatible

func Compatible() *tls.Config

Compatible is the tls config for compatible mode

func Global

func Global(ctx context.Context, key any) any

Global returns global value from context

func Modern

func Modern() *tls.Config

Modern is the tls config for modern mode

func Restricted

func Restricted() *tls.Config

Restricted is the tls config for restricted mode

func Route

func Route(ctx context.Context, name string, params ...any) string

Route returns route value from context

func SafeRedirectPath

func SafeRedirectPath(p string) string

SafeRedirectPath filters domain out from path

func StartHTTPSRedirectServer

func StartHTTPSRedirectServer(addr string) error

StartHTTPSRedirectServer starts http to https redirect server

Types

type App

type App struct {
	ETag bool
	// contains filtered or unexported fields
}

App is the hime app

func New

func New() *App

New creates new app

func (*App) Address

func (app *App) Address(addr string)

Address sets server address

func (*App) Clone

func (app *App) Clone() *App

Clone clones app

func (*App) Config

func (app *App) Config(config AppConfig)

Config merges config into app's config

Example:

globals:

data1: test

routes:

index: /
about: /about

templates:

  • dir: view root: layout delims: ["{{", "}}"] minify: true preload:
  • comp/comp1.tmpl
  • comp/comp2.tmpl list: main.tmpl:
  • main.tmpl
  • _layout.tmpl about.tmpl: [about.tmpl, _layout.tmpl]

func (*App) Global

func (app *App) Global(key any) any

Global gets value from global storage

func (*App) Globals

func (app *App) Globals(globals Globals)

Globals registers global constants

func (*App) Handler

func (app *App) Handler(h http.Handler)

Handler sets the handler

func (*App) ListenAndServe

func (app *App) ListenAndServe() error

ListenAndServe starts web server

func (*App) ParseConfig

func (app *App) ParseConfig(data []byte)

ParseConfig parses config data

func (*App) ParseConfigFile

func (app *App) ParseConfigFile(filename string)

ParseConfigFile parses config from file

func (*App) Route

func (app *App) Route(name string, params ...any) string

Route gets route path from given name

func (*App) Routes

func (app *App) Routes(routes Routes)

Routes registers route name and path

func (*App) SelfSign

func (app *App) SelfSign(s SelfSign)

SelfSign generates self sign cert

func (*App) Serve

func (app *App) Serve(l net.Listener) error

Serve serves listener

func (*App) ServeHTTP

func (app *App) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*App) ServeHandler

func (app *App) ServeHandler(h http.Handler) http.Handler

func (*App) Server

func (app *App) Server() *parapet.Server

Server returns server inside app

func (*App) SetServer

func (app *App) SetServer(srv *parapet.Server)

func (*App) Shutdown

func (app *App) Shutdown() error

Shutdown shutdowns server

func (*App) TLS

func (app *App) TLS(certFile, keyFile string)

TLS sets cert and key file

func (*App) Template

func (app *App) Template() *Template

Template creates new template loader

func (*App) TemplateFunc

func (app *App) TemplateFunc(name string, f any)

TemplateFunc registers an app's level template func

func (*App) TemplateFuncs

func (app *App) TemplateFuncs(funcs ...template.FuncMap)

TemplateFuncs registers app's level template funcs

type AppConfig

type AppConfig struct {
	Globals   Globals          `yaml:"globals" json:"globals"`
	Routes    Routes           `yaml:"routes" json:"routes"`
	Templates []TemplateConfig `yaml:"templates" json:"templates"`
}

AppConfig is hime app's config

type Context

type Context struct {
	*http.Request
	// contains filtered or unexported fields
}

Context is hime context

func NewAppContext

func NewAppContext(app *App, w http.ResponseWriter, r *http.Request) *Context

NewAppContext creates new hime's context with given app

func NewContext

func NewContext(w http.ResponseWriter, r *http.Request) *Context

NewContext creates new hime's context

func (*Context) AddCookie

func (ctx *Context) AddCookie(name string, value string, opts *CookieOptions)

func (*Context) AddHeader

func (ctx *Context) AddHeader(key, value string)

AddHeader adds a header to response

func (*Context) AddHeaderIfNotExists

func (ctx *Context) AddHeaderIfNotExists(key, value string)

AddHeaderIfNotExists adds a header to response if not exists

func (*Context) BindJSON

func (ctx *Context) BindJSON(v any) error

BindJSON binds request body using json decoder

func (*Context) Bytes

func (ctx *Context) Bytes(b []byte) error

Bytes writes bytes into response writer

func (*Context) Component

func (ctx *Context) Component(name string, data any) error

Component renders component

func (*Context) CookieValue

func (ctx *Context) CookieValue(name string) string

func (*Context) CopyFrom

func (ctx *Context) CopyFrom(src io.Reader) error

CopyFrom copies src reader into response writer

func (*Context) Deadline

func (ctx *Context) Deadline() (deadline time.Time, ok bool)

Deadline implements context.Context

func (*Context) DelCookie

func (ctx *Context) DelCookie(name string, opts *CookieOptions)

func (*Context) DelHeader

func (ctx *Context) DelHeader(key string)

DelHeader deletes a header from response

func (*Context) Done

func (ctx *Context) Done() <-chan struct{}

Done implements context.Context

func (*Context) ETag

func (ctx *Context) ETag(enable bool) *Context

ETag overrides etag setting

func (*Context) Err

func (ctx *Context) Err() error

Err implements context.Context

func (*Context) Error

func (ctx *Context) Error(error string) error

Error calls http.Error

func (*Context) File

func (ctx *Context) File(name string) error

File serves file using http.ServeFile

func (*Context) FormFileHeader

func (ctx *Context) FormFileHeader(key string) (*multipart.FileHeader, error)

FormFileHeader returns file header for given key without open file

func (*Context) FormFileHeaderNotEmpty

func (ctx *Context) FormFileHeaderNotEmpty(key string) (*multipart.FileHeader, error)

FormFileHeaderNotEmpty returns file header if not empty, or http.ErrMissingFile if file is empty

This function will be deprecated after drop go1.10 support, since go1.11 bring back old behavior

func (*Context) FormFileNotEmpty

func (ctx *Context) FormFileNotEmpty(key string) (multipart.File, *multipart.FileHeader, error)

FormFileNotEmpty returns file from r.FormFile only when file size is not empty, or return http.ErrMissingFile if file is empty

func (*Context) FormValueFloat32

func (ctx *Context) FormValueFloat32(key string) float32

FormValueFloat32 converts form value to float32

func (*Context) FormValueFloat64

func (ctx *Context) FormValueFloat64(key string) float64

FormValueFloat64 converts form value to float64

func (*Context) FormValueInt

func (ctx *Context) FormValueInt(key string) int

FormValueInt converts form value to int

func (*Context) FormValueInt64

func (ctx *Context) FormValueInt64(key string) int64

FormValueInt64 converts form value to int64

func (*Context) FormValueTrimSpace

func (ctx *Context) FormValueTrimSpace(key string) string

FormValueTrimSpace trims space from form value

func (*Context) FormValueTrimSpaceComma

func (ctx *Context) FormValueTrimSpaceComma(key string) string

FormValueTrimSpaceComma trims space and remove comma from form value

func (*Context) Global

func (ctx *Context) Global(key any) any

Global returns global value

func (*Context) HTML

func (ctx *Context) HTML(data string) error

HTML writes html to response writer

func (*Context) Handle

func (ctx *Context) Handle(h http.Handler) error

Handle calls h.ServeHTTP

func (*Context) JSON

func (ctx *Context) JSON(data any) error

JSON encodes given data into json then writes to response writer

func (*Context) NoContent

func (ctx *Context) NoContent() error

NoContent writes http.StatusNoContent into response writer

func (*Context) NotFound

func (ctx *Context) NotFound() error

NotFound calls http.NotFound

func (*Context) Param

func (ctx *Context) Param(name string, value any) *Param

Param is the short-hand for hime.Param

func (*Context) PostFormValueFloat32

func (ctx *Context) PostFormValueFloat32(key string) float32

PostFormValueFloat32 converts post form value to flost32

func (*Context) PostFormValueFloat64

func (ctx *Context) PostFormValueFloat64(key string) float64

PostFormValueFloat64 converts post form value to flost64

func (*Context) PostFormValueInt

func (ctx *Context) PostFormValueInt(key string) int

PostFormValueInt converts post form value to int

func (*Context) PostFormValueInt64

func (ctx *Context) PostFormValueInt64(key string) int64

PostFormValueInt64 converts post form value to int64

func (*Context) PostFormValueTrimSpace

func (ctx *Context) PostFormValueTrimSpace(key string) string

PostFormValueTrimSpace trims space from post form value

func (*Context) PostFormValueTrimSpaceComma

func (ctx *Context) PostFormValueTrimSpaceComma(key string) string

PostFormValueTrimSpaceComma trims space and remove comma from post form value

func (*Context) Redirect

func (ctx *Context) Redirect(url string, params ...any) error

Redirect redirects to given url

func (*Context) RedirectBack

func (ctx *Context) RedirectBack(fallback string) error

RedirectBack redirects to referer or fallback if referer not exists

func (*Context) RedirectBackToGet

func (ctx *Context) RedirectBackToGet() error

RedirectBackToGet redirects to referer or fallback with same url

func (*Context) RedirectTo

func (ctx *Context) RedirectTo(name string, params ...any) error

RedirectTo redirects to route name

func (*Context) RedirectToGet

func (ctx *Context) RedirectToGet() error

RedirectToGet redirects to same url back to Get

func (*Context) Render

func (ctx *Context) Render(tmpl string, data any) error

Render renders html template

func (*Context) ResponseWriter

func (ctx *Context) ResponseWriter() http.ResponseWriter

ResponseWriter returns response writer

func (*Context) Route

func (ctx *Context) Route(name string, params ...any) string

Route gets route path from name

func (*Context) SafeRedirect

func (ctx *Context) SafeRedirect(url string, params ...any) error

SafeRedirect extracts only path from url then redirect

func (*Context) SafeRedirectBack

func (ctx *Context) SafeRedirectBack(fallback string) error

SafeRedirectBack safe redirects to referer

func (*Context) SetHeader

func (ctx *Context) SetHeader(key, value string)

SetHeader sets a header to response

func (*Context) Status

func (ctx *Context) Status(code int) *Context

Status sets response status code

func (*Context) StatusText

func (ctx *Context) StatusText() error

StatusText writes status text from seted status code tnto response writer

func (*Context) String

func (ctx *Context) String(format string, a ...any) error

String writes string into response writer

func (*Context) Value

func (ctx *Context) Value(key any) any

Value implements context.Context

func (*Context) View

func (ctx *Context) View(name string, data any) error

View renders view

func (*Context) WithContext

func (ctx *Context) WithContext(nctx context.Context) *Context

WithContext returns new context with new request with given context

func (*Context) WithRequest

func (ctx *Context) WithRequest(r *http.Request) *Context

WithRequest returns new context with given request

func (*Context) WithResponseWriter

func (ctx *Context) WithResponseWriter(w http.ResponseWriter) *Context

WithResponseWriter returns new context with given response writer

func (*Context) WithValue

func (ctx *Context) WithValue(key any, val any) *Context

WithValue calls WithContext with value context

type CookieOptions

type CookieOptions struct {
	Path     string
	Domain   string
	MaxAge   int
	Secure   bool
	HttpOnly bool
	SameSite http.SameSite
}

type ErrComponentDuplicate

type ErrComponentDuplicate struct {
	Name string
}

ErrComponentDuplicate is the error for component duplicate

func (*ErrComponentDuplicate) Error

func (err *ErrComponentDuplicate) Error() string

type ErrComponentNotFound

type ErrComponentNotFound struct {
	Name string
}

ErrComponentNotFound is the error for component not found

func (*ErrComponentNotFound) Error

func (err *ErrComponentNotFound) Error() string

type ErrRouteNotFound

type ErrRouteNotFound struct {
	Route string
}

ErrRouteNotFound is the error for route not found

func (*ErrRouteNotFound) Error

func (err *ErrRouteNotFound) Error() string

type ErrTemplateDuplicate

type ErrTemplateDuplicate struct {
	Name string
}

ErrTemplateDuplicate is the error for template duplicate

func (*ErrTemplateDuplicate) Error

func (err *ErrTemplateDuplicate) Error() string

type ErrTemplateNotFound

type ErrTemplateNotFound struct {
	Name string
}

ErrTemplateNotFound is the error for template not found

func (*ErrTemplateNotFound) Error

func (err *ErrTemplateNotFound) Error() string

type Globals

type Globals map[any]any

Globals is the global const map

type HTTPSRedirect

type HTTPSRedirect struct {
	Addr string `json:"addr"`
}

HTTPSRedirect type

func (*HTTPSRedirect) ServeHTTP

func (s *HTTPSRedirect) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (HTTPSRedirect) Server

func (s HTTPSRedirect) Server() *http.Server

Server generates https redirect server

type Handler

type Handler func(*Context) error

Handler is the hime handler

func (Handler) ServeHTTP

func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request)

type Param

type Param struct {
	Name  string
	Value any
}

Param is the query param when redirect

type Routes

type Routes map[string]string

Routes is the map for route name => path

type SelfSign

type SelfSign struct {
	Key struct {
		Algo string `yaml:"algo" json:"algo"`
		Size int    `yaml:"size" json:"size"`
	} `yaml:"key" json:"key"`
	CN    string   `yaml:"cn" json:"cn"`
	Hosts []string `yaml:"host" json:"host"`
}

SelfSign type

type TLS

type TLS struct {
	SelfSign   *SelfSign `yaml:"selfSign" json:"selfSign"`
	CertFile   string    `yaml:"certFile" json:"certFile"`
	KeyFile    string    `yaml:"keyFile" json:"keyFile"`
	Profile    string    `yaml:"profile" json:"profile"`
	MinVersion string    `yaml:"minVersion" json:"minVersion"`
	MaxVersion string    `yaml:"maxVersion" json:"maxVersion"`
	Curves     []string  `yaml:"curves" json:"curves"`
}

TLS type

type Template

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

Template is template loader

func (*Template) Component

func (tp *Template) Component(ts ...*template.Template)

Component loads html/template into component list

func (*Template) Config

func (tp *Template) Config(cfg TemplateConfig)

Config loads template config

func (*Template) Delims

func (tp *Template) Delims(left, right string)

Delims sets left and right delims

func (*Template) Dir

func (tp *Template) Dir(path string)

Dir sets root directory when load template

default is ""

func (*Template) FS

func (tp *Template) FS(fs fs.FS)

FS uses fs when load template

func (*Template) Func

func (tp *Template) Func(name string, f any)

Func adds a template func while load template

func (*Template) Funcs

func (tp *Template) Funcs(funcs ...template.FuncMap)

Funcs adds template funcs while load template

func (*Template) Minify

func (tp *Template) Minify()

Minify enables minify when render html, css, js, must call before parse

func (*Template) MinifyWith

func (tp *Template) MinifyWith(cfg TemplateMinifyConfig)

MinifyWith enables minify with custom options, must call before parse

func (*Template) Parse

func (tp *Template) Parse(name string, text string)

Parse parses template from text

func (*Template) ParseComponent

func (tp *Template) ParseComponent(name string, text string)

ParseComponent parses component from text

func (*Template) ParseComponentFile

func (tp *Template) ParseComponentFile(name string, filename string)

ParseComponentFile loads component from file

func (*Template) ParseConfig

func (tp *Template) ParseConfig(data []byte)

ParseConfig parses template config data

func (*Template) ParseConfigFile

func (tp *Template) ParseConfigFile(filename string)

ParseConfigFile parses template config from file

func (*Template) ParseFiles

func (tp *Template) ParseFiles(name string, filenames ...string)

ParseFiles loads template from file

func (*Template) ParseGlob

func (tp *Template) ParseGlob(name string, pattern string)

ParseGlob loads template from pattern

func (*Template) Preload

func (tp *Template) Preload(filename ...string)

Preload loads given templates before parse

func (*Template) Root

func (tp *Template) Root(name string)

Root calls t.Lookup(name) after load template, empty string won't trigger t.Lookup

default is ""

type TemplateConfig

type TemplateConfig struct {
	Dir     string              `yaml:"dir" json:"dir"`
	Root    string              `yaml:"root" json:"root"`
	Minify  bool                `yaml:"minify" json:"minify"`
	Preload []string            `yaml:"preload" json:"preload"`
	List    map[string][]string `yaml:"list" json:"list"`
	Delims  []string            `yaml:"delims" json:"delims"`
}

TemplateConfig is template config

type TemplateMinifyConfig

type TemplateMinifyConfig struct {
	HTML minify.Minifier
	CSS  minify.Minifier
	JS   minify.Minifier
}

Jump to

Keyboard shortcuts

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