http

package
v0.9.3 Latest Latest
Warning

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

Go to latest
Published: Aug 4, 2026 License: MIT Imports: 62 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrorMiddleware = func(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		ctx := context.WithValue(r.Context(), "error-handler", func(err error) {
			slog.Error(err.Error(), "request_id", r.Header.Get("X-Request-Id"))

			httputil.HandleError(w, httputil.NewError("", err, http.StatusInternalServerError))
		})

		next.ServeHTTP(w, r.WithContext(ctx))
	})
}
View Source
var PostMiddleware = func(_ http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		w.WriteHeader(http.StatusNoContent)
		_, _ = w.Write(nil)
	})
}
View Source
var PreMiddleware = func(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		_, r = tcontext.New(w, r)

		next.ServeHTTP(w, r)
	})
}
View Source
var ReadHeaderTimeout = 10 * time.Second
View Source
var RecoverMiddleware = func(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		defer func() {
			if r := recover(); r != nil {
				if r == http.ErrAbortHandler {
					panic(r)
				}
				err, ok := r.(error)
				if !ok {
					err = fmt.Errorf("%v", r)
				}

				slog.Error(fmt.Sprintf("panic: %s", err.Error()))
				debug.PrintStack()

				w.WriteHeader(http.StatusInternalServerError)
				_, _ = w.Write([]byte(fmt.Sprintf("panic: %s", err.Error())))

				return
			}
		}()

		next.ServeHTTP(w, r)
	})
}
View Source
var ServerInfo = "turna"
View Source
var ServerInfoMiddleware = func(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Server", ServerInfo)

		next.ServeHTTP(w, r)
	})
}

Functions

This section is empty.

Types

type ACME added in v0.9.0

type ACME struct {
	// Enabled turns on ACME certificate provisioning.
	Enabled bool `cfg:"enabled"`
	// Email is the contact address registered with the ACME account.
	Email string `cfg:"email"`
	// Domains is the allow-list of host names ACME certificates may be issued
	// for (HostWhitelist). A request for a host outside this list is rejected.
	Domains []string `cfg:"domains"`
	// CacheDir is the directory used to persist account keys and issued
	// certificates. Defaults to "acme-cache".
	CacheDir string `cfg:"cache_dir"`
	// DirectoryURL overrides the ACME directory endpoint. Leave empty for the
	// Let's Encrypt production CA. Use the staging URL while testing to avoid
	// rate limits: https://acme-staging-v02.api.letsencrypt.org/directory
	DirectoryURL string `cfg:"directory_url"`
}

ACME configures automatic certificate provisioning from an ACME CA (e.g. Let's Encrypt) using the TLS-ALPN-01 challenge over the existing TLS entrypoint. No extra HTTP port is required, but the TLS entrypoint (usually :443) must be reachable from the public internet for validation to succeed.

type Certificate

type Certificate struct {
	CertFile string `cfg:"cert_file"`
	KeyFile  string `cfg:"key_file"`
}

type HTTP

type HTTP struct {
	Routers     map[string]Router         `cfg:"routers"`
	Middlewares map[string]HTTPMiddleware `cfg:"middlewares"`
	TLS         TLS                       `cfg:"tls"`
}

func (*HTTP) Set

func (h *HTTP) Set(ctx context.Context, wg *sync.WaitGroup) error

type HTTPMiddleware

type HTTPMiddleware struct {
	AddPrefixMiddleware        *addprefix.AddPrefix                  `cfg:"add_prefix"`
	InjectMiddleware           *inject.Inject                        `cfg:"inject"`
	HelloMiddleware            *hello.Hello                          `cfg:"hello"`
	TemplateMiddleware         *template.Template                    `cfg:"template"`
	InfoMiddleware             *info.Info                            `cfg:"info"`
	SetMiddleware              *set.Set                              `cfg:"set"`
	StripPrefixMiddleware      *stripprefix.StripPrefix              `cfg:"strip_prefix"`
	RoleMiddleware             *role.Role                            `cfg:"role"`
	ScopeMiddleware            *scope.Scope                          `cfg:"scope"`
	ServiceMiddleware          *service.Service                      `cfg:"service"`
	FolderMiddleware           *folder.Folder                        `cfg:"folder"`
	BasicAuthMiddleware        *basicauth.BasicAuth                  `cfg:"basic_auth"`
	CorsMiddleware             *cors.Cors                            `cfg:"cors"`
	HeadersMiddleware          *headers.Headers                      `cfg:"headers"`
	BlockMiddleware            *block.Block                          `cfg:"block"`
	RegexPathMiddleware        *regexpath.RegexPath                  `cfg:"regex_path"`
	GzipMiddleware             *gzip.Gzip                            `cfg:"gzip"`
	DecompressMiddleware       *decompress.Decompress                `cfg:"decompress"`
	LogMiddleware              *log.Log                              `cfg:"log"`
	PrintMiddleware            *print.Print                          `cfg:"print"`
	LoginMiddleware            *login.Login                          `cfg:"login"`
	SessionMiddleware          *session.Session                      `cfg:"session"`
	ViewMiddleware             *view.View                            `cfg:"view"`
	RequestMiddleware          *request.Request                      `cfg:"request"`
	RedirectionMiddleware      *redirection.Redirection              `cfg:"redirection"`
	TryMiddleware              *try.Try                              `cfg:"try"`
	SessionInfoMiddleware      *sessioninfo.Info                     `cfg:"session_info"`
	IamMiddleware              *iam.Iam                              `cfg:"iam"`
	IamCheckMiddleware         *iamcheck.IamCheck                    `cfg:"iam_check"`
	IamForwardAuthMiddleware   *iamforwardauth.IamForwardAuth        `cfg:"iam_forward_auth"`
	RoleCheckMiddleware        *rolecheck.RoleCheck                  `cfg:"role_check"`
	RoleDataMiddleware         *roledata.RoleData                    `cfg:"role_data"`
	TokenPassMiddleware        *tokenpass.TokenPass                  `cfg:"token_pass"`
	RedirectContinueMiddleware *redirectcontinue.RedirectionContinue `cfg:"redirect_continue"`
	ForwardMiddleware          *forward.Forward                      `cfg:"forward"`
	GrpcUIMiddleware           *grpcui.GrpcUI                        `cfg:"grpcui"`
	DNSPathMiddleware          *dnspath.DNSPath                      `cfg:"dns_path"`
	SplitterMiddleware         *splitter.Splitter                    `cfg:"splitter"`
	PathMiddleware             *path.Path                            `cfg:"path"`
	RequestIDMiddleware        *requestid.RequestID                  `cfg:"request_id"`
	Oauth2                     *oauth2.Oauth2                        `cfg:"oauth2"`
	AccessLogMiddleware        *accesslog.AccessLog                  `cfg:"access_log"`
	URL                        *url.URL                              `cfg:"url"`
	RateLimit                  *ratelimit.RateLimit                  `cfg:"rate_limit"`
	Auth                       *auth.Auth                            `cfg:"auth"`
}

func (*HTTPMiddleware) Set

func (h *HTTPMiddleware) Set(ctx context.Context, name string) error

type MiddlewareFunc added in v0.7.0

type MiddlewareFunc = func(http.Handler) http.Handler

type PreMiddlewares added in v0.7.8

type PreMiddlewares struct {
	RequestID  *bool `cfg:"request_id"`  // default is true
	ServerInfo *bool `cfg:"server_info"` // default is true
}

type Router

type Router struct {
	Host        string    `cfg:"host"`
	Path        []string  `cfg:"path"`
	Middlewares []string  `cfg:"middlewares"`
	TLS         *struct{} `cfg:"tls"`
	EntryPoints []string  `cfg:"entrypoints"`

	PreMiddlewares PreMiddlewares `cfg:"pre_middlewares"`
}

func (*Router) Set

func (r *Router) Set(_ string, ruleRouter *RuleRouter) error

type RouterHandler added in v0.7.1

type RouterHandler interface {
	Handle(pattern string, handler http.Handler, middlewares ...func(http.Handler) http.Handler)
	ServeHTTP(w http.ResponseWriter, r *http.Request)
}

type RuleRouter

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

func NewRuleRouter

func NewRuleRouter() *RuleRouter

func (*RuleRouter) GetMux added in v0.7.0

func (s *RuleRouter) GetMux(r RuleSelection) RouterHandler

func (RuleRouter) Serve

func (s RuleRouter) Serve(entrypoint string) http.Handler

Serve implements the http.Handler interface with changing entrypoint selection.

func (*RuleRouter) ServeHTTP

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

func (*RuleRouter) SetRule

func (s *RuleRouter) SetRule(selection RuleSelection)

type RuleSelection

type RuleSelection struct {
	Host       string
	Entrypoint string
}

type SelfSigned added in v0.9.0

type SelfSigned struct {
	Organization []string `cfg:"organization"`
	DNSNames     []string `cfg:"dns_names"`
	IPs          []string `cfg:"ips"`
}

type TLS

type TLS struct {
	// Store maps an SNI host name to its certificate(s). The special key
	// "default" is used as the fallback when the client sends no SNI server
	// name or no host entry matches.
	Store map[string][]Certificate `cfg:"store"`
	// MinVersion is the minimum accepted TLS version: "1.2" or "1.3".
	// Defaults to "1.3".
	MinVersion string `cfg:"min_version"`
	// SelfSigned customizes the auto-generated certificate used when no
	// certificate is configured in Store.
	SelfSigned SelfSigned `cfg:"self_signed"`
	// ACME enables automatic certificate provisioning from an ACME CA such as
	// Let's Encrypt using the TLS-ALPN-01 challenge.
	ACME *ACME `cfg:"acme"`
}

Jump to

Keyboard shortcuts

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