MSP-8974 add download flow, server migration to http

This commit is contained in:
chashintv committed 2026-11-23 12:54:59 +03:00
1 parent aa68f6028a
commit 71498785ea
46 files changed
+5102 -124

No files matched your search

+18
View File
@@ -0,0 +1,18 @@
sudo: false
language: go
go:
- 1.7.x
- 1.8.x
- 1.9.x
- 1.10.x
- 1.11.x
- 1.12.x
- 1.13.x
- master
before_install:
- go get github.com/mattn/goveralls
script:
- go test -v -covermode=count -coverprofile=coverage.out
- go vet ./...
- test -z "$(gofmt -d -s . | tee /dev/stderr)"
- $HOME/gopath/bin/goveralls -coverprofile=coverage.out -service=travis-ci
+29
View File
@@ -0,0 +1,29 @@
BSD 3-Clause License
Copyright (c) 2013, Julien Schmidt
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+300
View File
@@ -0,0 +1,300 @@
# HttpRouter [![Build Status](https://travis-ci.org/julienschmidt/httprouter.svg?branch=master)](https://travis-ci.org/julienschmidt/httprouter) [![Coverage Status](https://coveralls.io/repos/github/julienschmidt/httprouter/badge.svg?branch=master)](https://coveralls.io/github/julienschmidt/httprouter?branch=master) [![GoDoc](https://godoc.org/github.com/julienschmidt/httprouter?status.svg)](http://godoc.org/github.com/julienschmidt/httprouter)
HttpRouter is a lightweight high performance HTTP request router (also called *multiplexer* or just *mux* for short) for [Go](https://golang.org/).
In contrast to the [default mux](https://golang.org/pkg/net/http/#ServeMux) of Go's `net/http` package, this router supports variables in the routing pattern and matches against the request method. It also scales better.
The router is optimized for high performance and a small memory footprint. It scales well even with very long paths and a large number of routes. A compressing dynamic trie (radix tree) structure is used for efficient matching.
## Features
**Only explicit matches:** With other routers, like [`http.ServeMux`](https://golang.org/pkg/net/http/#ServeMux), a requested URL path could match multiple patterns. Therefore they have some awkward pattern priority rules, like *longest match* or *first registered, first matched*. By design of this router, a request can only match exactly one or no route. As a result, there are also no unintended matches, which makes it great for SEO and improves the user experience.
**Stop caring about trailing slashes:** Choose the URL style you like, the router automatically redirects the client if a trailing slash is missing or if there is one extra. Of course it only does so, if the new path has a handler. If you don't like it, you can [turn off this behavior](https://godoc.org/github.com/julienschmidt/httprouter#Router.RedirectTrailingSlash).
**Path auto-correction:** Besides detecting the missing or additional trailing slash at no extra cost, the router can also fix wrong cases and remove superfluous path elements (like `../` or `//`). Is [CAPTAIN CAPS LOCK](http://www.urbandictionary.com/define.php?term=Captain+Caps+Lock) one of your users? HttpRouter can help him by making a case-insensitive look-up and redirecting him to the correct URL.
**Parameters in your routing pattern:** Stop parsing the requested URL path, just give the path segment a name and the router delivers the dynamic value to you. Because of the design of the router, path parameters are very cheap.
**Zero Garbage:** The matching and dispatching process generates zero bytes of garbage. The only heap allocations that are made are building the slice of the key-value pairs for path parameters, and building new context and request objects (the latter only in the standard `Handler`/`HandlerFunc` API). In the 3-argument API, if the request path contains no parameters not a single heap allocation is necessary.
**Best Performance:** [Benchmarks speak for themselves](https://github.com/julienschmidt/go-http-routing-benchmark). See below for technical details of the implementation.
**No more server crashes:** You can set a [Panic handler](https://godoc.org/github.com/julienschmidt/httprouter#Router.PanicHandler) to deal with panics occurring during handling a HTTP request. The router then recovers and lets the `PanicHandler` log what happened and deliver a nice error page.
**Perfect for APIs:** The router design encourages to build sensible, hierarchical RESTful APIs. Moreover it has built-in native support for [OPTIONS requests](http://zacstewart.com/2012/04/14/http-options-method.html) and `405 Method Not Allowed` replies.
Of course you can also set **custom [`NotFound`](https://godoc.org/github.com/julienschmidt/httprouter#Router.NotFound) and [`MethodNotAllowed`](https://godoc.org/github.com/julienschmidt/httprouter#Router.MethodNotAllowed) handlers** and [**serve static files**](https://godoc.org/github.com/julienschmidt/httprouter#Router.ServeFiles).
## Usage
This is just a quick introduction, view the [GoDoc](http://godoc.org/github.com/julienschmidt/httprouter) for details.
Let's start with a trivial example:
```go
package main
import (
"fmt"
"net/http"
"log"
"github.com/julienschmidt/httprouter"
)
func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
fmt.Fprint(w, "Welcome!\n")
}
func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name"))
}
func main() {
router := httprouter.New()
router.GET("/", Index)
router.GET("/hello/:name", Hello)
log.Fatal(http.ListenAndServe(":8080", router))
}
```
### Named parameters
As you can see, `:name` is a *named parameter*. The values are accessible via `httprouter.Params`, which is just a slice of `httprouter.Param`s. You can get the value of a parameter either by its index in the slice, or by using the `ByName(name)` method: `:name` can be retrieved by `ByName("name")`.
When using a `http.Handler` (using `router.Handler` or `http.HandlerFunc`) instead of HttpRouter's handle API using a 3rd function parameter, the named parameters are stored in the `request.Context`. See more below under [Why doesn't this work with http.Handler?](#why-doesnt-this-work-with-httphandler).
Named parameters only match a single path segment:
```
Pattern: /user/:user
/user/gordon match
/user/you match
/user/gordon/profile no match
/user/ no match
```
**Note:** Since this router has only explicit matches, you can not register static routes and parameters for the same path segment. For example you can not register the patterns `/user/new` and `/user/:user` for the same request method at the same time. The routing of different request methods is independent from each other.
### Catch-All parameters
The second type are *catch-all* parameters and have the form `*name`. Like the name suggests, they match everything. Therefore they must always be at the **end** of the pattern:
```
Pattern: /src/*filepath
/src/ match
/src/somefile.go match
/src/subdir/somefile.go match
```
## How does it work?
The router relies on a tree structure which makes heavy use of *common prefixes*, it is basically a *compact* [*prefix tree*](https://en.wikipedia.org/wiki/Trie) (or just [*Radix tree*](https://en.wikipedia.org/wiki/Radix_tree)). Nodes with a common prefix also share a common parent. Here is a short example what the routing tree for the `GET` request method could look like:
```
Priority Path Handle
9 \ *<1>
3 ├s nil
2 |├earch\ *<2>
1 |└upport\ *<3>
2 ├blog\ *<4>
1 | └:post nil
1 | └\ *<5>
2 ├about-us\ *<6>
1 | └team\ *<7>
1 └contact\ *<8>
```
Every `*<num>` represents the memory address of a handler function (a pointer). If you follow a path trough the tree from the root to the leaf, you get the complete route path, e.g `\blog\:post\`, where `:post` is just a placeholder ([*parameter*](#named-parameters)) for an actual post name. Unlike hash-maps, a tree structure also allows us to use dynamic parts like the `:post` parameter, since we actually match against the routing patterns instead of just comparing hashes. [As benchmarks show](https://github.com/julienschmidt/go-http-routing-benchmark), this works very well and efficient.
Since URL paths have a hierarchical structure and make use only of a limited set of characters (byte values), it is very likely that there are a lot of common prefixes. This allows us to easily reduce the routing into ever smaller problems. Moreover the router manages a separate tree for every request method. For one thing it is more space efficient than holding a method->handle map in every single node, it also allows us to greatly reduce the routing problem before even starting the look-up in the prefix-tree.
For even better scalability, the child nodes on each tree level are ordered by priority, where the priority is just the number of handles registered in sub nodes (children, grandchildren, and so on..). This helps in two ways:
1. Nodes which are part of the most routing paths are evaluated first. This helps to make as much routes as possible to be reachable as fast as possible.
2. It is some sort of cost compensation. The longest reachable path (highest cost) can always be evaluated first. The following scheme visualizes the tree structure. Nodes are evaluated from top to bottom and from left to right.
```
├------------
├---------
├-----
├----
├--
├--
└-
```
## Why doesn't this work with `http.Handler`?
**It does!** The router itself implements the `http.Handler` interface. Moreover the router provides convenient [adapters for `http.Handler`](https://godoc.org/github.com/julienschmidt/httprouter#Router.Handler)s and [`http.HandlerFunc`](https://godoc.org/github.com/julienschmidt/httprouter#Router.HandlerFunc)s which allows them to be used as a [`httprouter.Handle`](https://godoc.org/github.com/julienschmidt/httprouter#Router.Handle) when registering a route.
Named parameters can be accessed `request.Context`:
```go
func Hello(w http.ResponseWriter, r *http.Request) {
params := httprouter.ParamsFromContext(r.Context())
fmt.Fprintf(w, "hello, %s!\n", params.ByName("name"))
}
```
Alternatively, one can also use `params := r.Context().Value(httprouter.ParamsKey)` instead of the helper function.
Just try it out for yourself, the usage of HttpRouter is very straightforward. The package is compact and minimalistic, but also probably one of the easiest routers to set up.
## Automatic OPTIONS responses and CORS
One might wish to modify automatic responses to OPTIONS requests, e.g. to support [CORS preflight requests](https://developer.mozilla.org/en-US/docs/Glossary/preflight_request) or to set other headers.
This can be achieved using the [`Router.GlobalOPTIONS`](https://godoc.org/github.com/julienschmidt/httprouter#Router.GlobalOPTIONS) handler:
```go
router.GlobalOPTIONS = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Access-Control-Request-Method") != "" {
// Set CORS headers
header := w.Header()
header.Set("Access-Control-Allow-Methods", r.Header.Get("Allow"))
header.Set("Access-Control-Allow-Origin", "*")
}
// Adjust status code to 204
w.WriteHeader(http.StatusNoContent)
})
```
## Where can I find Middleware *X*?
This package just provides a very efficient request router with a few extra features. The router is just a [`http.Handler`](https://golang.org/pkg/net/http/#Handler), you can chain any http.Handler compatible middleware before the router, for example the [Gorilla handlers](http://www.gorillatoolkit.org/pkg/handlers). Or you could [just write your own](https://justinas.org/writing-http-middleware-in-go/), it's very easy!
Alternatively, you could try [a web framework based on HttpRouter](#web-frameworks-based-on-httprouter).
### Multi-domain / Sub-domains
Here is a quick example: Does your server serve multiple domains / hosts?
You want to use sub-domains?
Define a router per host!
```go
// We need an object that implements the http.Handler interface.
// Therefore we need a type for which we implement the ServeHTTP method.
// We just use a map here, in which we map host names (with port) to http.Handlers
type HostSwitch map[string]http.Handler
// Implement the ServeHTTP method on our new type
func (hs HostSwitch) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Check if a http.Handler is registered for the given host.
// If yes, use it to handle the request.
if handler := hs[r.Host]; handler != nil {
handler.ServeHTTP(w, r)
} else {
// Handle host names for which no handler is registered
http.Error(w, "Forbidden", 403) // Or Redirect?
}
}
func main() {
// Initialize a router as usual
router := httprouter.New()
router.GET("/", Index)
router.GET("/hello/:name", Hello)
// Make a new HostSwitch and insert the router (our http handler)
// for example.com and port 12345
hs := make(HostSwitch)
hs["example.com:12345"] = router
// Use the HostSwitch to listen and serve on port 12345
log.Fatal(http.ListenAndServe(":12345", hs))
}
```
### Basic Authentication
Another quick example: Basic Authentication (RFC 2617) for handles:
```go
package main
import (
"fmt"
"log"
"net/http"
"github.com/julienschmidt/httprouter"
)
func BasicAuth(h httprouter.Handle, requiredUser, requiredPassword string) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
// Get the Basic Authentication credentials
user, password, hasAuth := r.BasicAuth()
if hasAuth && user == requiredUser && password == requiredPassword {
// Delegate request to the given handle
h(w, r, ps)
} else {
// Request Basic Authentication otherwise
w.Header().Set("WWW-Authenticate", "Basic realm=Restricted")
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
}
}
}
func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
fmt.Fprint(w, "Not protected!\n")
}
func Protected(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
fmt.Fprint(w, "Protected!\n")
}
func main() {
user := "gordon"
pass := "secret!"
router := httprouter.New()
router.GET("/", Index)
router.GET("/protected/", BasicAuth(Protected, user, pass))
log.Fatal(http.ListenAndServe(":8080", router))
}
```
## Chaining with the NotFound handler
**NOTE: It might be required to set [`Router.HandleMethodNotAllowed`](https://godoc.org/github.com/julienschmidt/httprouter#Router.HandleMethodNotAllowed) to `false` to avoid problems.**
You can use another [`http.Handler`](https://golang.org/pkg/net/http/#Handler), for example another router, to handle requests which could not be matched by this router by using the [`Router.NotFound`](https://godoc.org/github.com/julienschmidt/httprouter#Router.NotFound) handler. This allows chaining.
### Static files
The `NotFound` handler can for example be used to serve static files from the root path `/` (like an `index.html` file along with other assets):
```go
// Serve static files from the ./public directory
router.NotFound = http.FileServer(http.Dir("public"))
```
But this approach sidesteps the strict core rules of this router to avoid routing problems. A cleaner approach is to use a distinct sub-path for serving files, like `/static/*filepath` or `/files/*filepath`.
## Web Frameworks based on HttpRouter
If the HttpRouter is a bit too minimalistic for you, you might try one of the following more high-level 3rd-party web frameworks building upon the HttpRouter package:
* [Ace](https://github.com/plimble/ace): Blazing fast Go Web Framework
* [api2go](https://github.com/manyminds/api2go): A JSON API Implementation for Go
* [Gin](https://github.com/gin-gonic/gin): Features a martini-like API with much better performance
* [Goat](https://github.com/bahlo/goat): A minimalistic REST API server in Go
* [goMiddlewareChain](https://github.com/TobiEiss/goMiddlewareChain): An express.js-like-middleware-chain
* [Hikaru](https://github.com/najeira/hikaru): Supports standalone and Google AppEngine
* [Hitch](https://github.com/nbio/hitch): Hitch ties httprouter, [httpcontext](https://github.com/nbio/httpcontext), and middleware up in a bow
* [httpway](https://github.com/corneldamian/httpway): Simple middleware extension with context for httprouter and a server with gracefully shutdown support
* [kami](https://github.com/guregu/kami): A tiny web framework using x/net/context
* [Medeina](https://github.com/imdario/medeina): Inspired by Ruby's Roda and Cuba
* [Neko](https://github.com/rocwong/neko): A lightweight web application framework for Golang
* [pbgo](https://github.com/chai2010/pbgo): pbgo is a mini RPC/REST framework based on Protobuf
* [River](https://github.com/abiosoft/river): River is a simple and lightweight REST server
* [siesta](https://github.com/VividCortex/siesta): Composable HTTP handlers with contexts
* [xmux](https://github.com/rs/xmux): xmux is a httprouter fork on top of xhandler (net/context aware)
+123
View File
@@ -0,0 +1,123 @@
// Copyright 2013 Julien Schmidt. All rights reserved.
// Based on the path package, Copyright 2009 The Go Authors.
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file.
package httprouter
// CleanPath is the URL version of path.Clean, it returns a canonical URL path
// for p, eliminating . and .. elements.
//
// The following rules are applied iteratively until no further processing can
// be done:
// 1. Replace multiple slashes with a single slash.
// 2. Eliminate each . path name element (the current directory).
// 3. Eliminate each inner .. path name element (the parent directory)
// along with the non-.. element that precedes it.
// 4. Eliminate .. elements that begin a rooted path:
// that is, replace "/.." by "/" at the beginning of a path.
//
// If the result of this process is an empty string, "/" is returned
func CleanPath(p string) string {
// Turn empty string into "/"
if p == "" {
return "/"
}
n := len(p)
var buf []byte
// Invariants:
// reading from path; r is index of next byte to process.
// writing to buf; w is index of next byte to write.
// path must start with '/'
r := 1
w := 1
if p[0] != '/' {
r = 0
buf = make([]byte, n+1)
buf[0] = '/'
}
trailing := n > 1 && p[n-1] == '/'
// A bit more clunky without a 'lazybuf' like the path package, but the loop
// gets completely inlined (bufApp). So in contrast to the path package this
// loop has no expensive function calls (except 1x make)
for r < n {
switch {
case p[r] == '/':
// empty path element, trailing slash is added after the end
r++
case p[r] == '.' && r+1 == n:
trailing = true
r++
case p[r] == '.' && p[r+1] == '/':
// . element
r += 2
case p[r] == '.' && p[r+1] == '.' && (r+2 == n || p[r+2] == '/'):
// .. element: remove to last /
r += 3
if w > 1 {
// can backtrack
w--
if buf == nil {
for w > 1 && p[w] != '/' {
w--
}
} else {
for w > 1 && buf[w] != '/' {
w--
}
}
}
default:
// real path element.
// add slash if needed
if w > 1 {
bufApp(&buf, p, w, '/')
w++
}
// copy element
for r < n && p[r] != '/' {
bufApp(&buf, p, w, p[r])
w++
r++
}
}
}
// re-append trailing slash
if trailing && w > 1 {
bufApp(&buf, p, w, '/')
w++
}
if buf == nil {
return p[:w]
}
return string(buf[:w])
}
// internal helper to lazily create a buffer if necessary
func bufApp(buf *[]byte, s string, w int, c byte) {
if *buf == nil {
if s[w] == c {
return
}
*buf = make([]byte, len(s))
copy(*buf, s[:w])
}
(*buf)[w] = c
}
+452
View File
@@ -0,0 +1,452 @@
// Copyright 2013 Julien Schmidt. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file.
// Package httprouter is a trie based high performance HTTP request router.
//
// A trivial example is:
//
// package main
//
// import (
// "fmt"
// "github.com/julienschmidt/httprouter"
// "net/http"
// "log"
// )
//
// func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
// fmt.Fprint(w, "Welcome!\n")
// }
//
// func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
// fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name"))
// }
//
// func main() {
// router := httprouter.New()
// router.GET("/", Index)
// router.GET("/hello/:name", Hello)
//
// log.Fatal(http.ListenAndServe(":8080", router))
// }
//
// The router matches incoming requests by the request method and the path.
// If a handle is registered for this path and method, the router delegates the
// request to that function.
// For the methods GET, POST, PUT, PATCH and DELETE shortcut functions exist to
// register handles, for all other methods router.Handle can be used.
//
// The registered path, against which the router matches incoming requests, can
// contain two types of parameters:
// Syntax Type
// :name named parameter
// *name catch-all parameter
//
// Named parameters are dynamic path segments. They match anything until the
// next '/' or the path end:
// Path: /blog/:category/:post
//
// Requests:
// /blog/go/request-routers match: category="go", post="request-routers"
// /blog/go/request-routers/ no match, but the router would redirect
// /blog/go/ no match
// /blog/go/request-routers/comments no match
//
// Catch-all parameters match anything until the path end, including the
// directory index (the '/' before the catch-all). Since they match anything
// until the end, catch-all parameters must always be the final path element.
// Path: /files/*filepath
//
// Requests:
// /files/ match: filepath="/"
// /files/LICENSE match: filepath="/LICENSE"
// /files/templates/article.html match: filepath="/templates/article.html"
// /files no match, but the router would redirect
//
// The value of parameters is saved as a slice of the Param struct, consisting
// each of a key and a value. The slice is passed to the Handle func as a third
// parameter.
// There are two ways to retrieve the value of a parameter:
// // by the name of the parameter
// user := ps.ByName("user") // defined by :user or *user
//
// // by the index of the parameter. This way you can also get the name (key)
// thirdKey := ps[2].Key // the name of the 3rd parameter
// thirdValue := ps[2].Value // the value of the 3rd parameter
package httprouter
import (
"context"
"net/http"
"strings"
)
// Handle is a function that can be registered to a route to handle HTTP
// requests. Like http.HandlerFunc, but has a third parameter for the values of
// wildcards (variables).
type Handle func(http.ResponseWriter, *http.Request, Params)
// Param is a single URL parameter, consisting of a key and a value.
type Param struct {
Key string
Value string
}
// Params is a Param-slice, as returned by the router.
// The slice is ordered, the first URL parameter is also the first slice value.
// It is therefore safe to read values by the index.
type Params []Param
// ByName returns the value of the first Param which key matches the given name.
// If no matching Param is found, an empty string is returned.
func (ps Params) ByName(name string) string {
for i := range ps {
if ps[i].Key == name {
return ps[i].Value
}
}
return ""
}
type paramsKey struct{}
// ParamsKey is the request context key under which URL params are stored.
var ParamsKey = paramsKey{}
// ParamsFromContext pulls the URL parameters from a request context,
// or returns nil if none are present.
func ParamsFromContext(ctx context.Context) Params {
p, _ := ctx.Value(ParamsKey).(Params)
return p
}
// Router is a http.Handler which can be used to dispatch requests to different
// handler functions via configurable routes
type Router struct {
trees map[string]*node
// Enables automatic redirection if the current route can't be matched but a
// handler for the path with (without) the trailing slash exists.
// For example if /foo/ is requested but a route only exists for /foo, the
// client is redirected to /foo with http status code 301 for GET requests
// and 307 for all other request methods.
RedirectTrailingSlash bool
// If enabled, the router tries to fix the current request path, if no
// handle is registered for it.
// First superfluous path elements like ../ or // are removed.
// Afterwards the router does a case-insensitive lookup of the cleaned path.
// If a handle can be found for this route, the router makes a redirection
// to the corrected path with status code 301 for GET requests and 307 for
// all other request methods.
// For example /FOO and /..//Foo could be redirected to /foo.
// RedirectTrailingSlash is independent of this option.
RedirectFixedPath bool
// If enabled, the router checks if another method is allowed for the
// current route, if the current request can not be routed.
// If this is the case, the request is answered with 'Method Not Allowed'
// and HTTP status code 405.
// If no other Method is allowed, the request is delegated to the NotFound
// handler.
HandleMethodNotAllowed bool
// If enabled, the router automatically replies to OPTIONS requests.
// Custom OPTIONS handlers take priority over automatic replies.
HandleOPTIONS bool
// An optional http.Handler that is called on automatic OPTIONS requests.
// The handler is only called if HandleOPTIONS is true and no OPTIONS
// handler for the specific path was set.
// The "Allowed" header is set before calling the handler.
GlobalOPTIONS http.Handler
// Cached value of global (*) allowed methods
globalAllowed string
// Configurable http.Handler which is called when no matching route is
// found. If it is not set, http.NotFound is used.
NotFound http.Handler
// Configurable http.Handler which is called when a request
// cannot be routed and HandleMethodNotAllowed is true.
// If it is not set, http.Error with http.StatusMethodNotAllowed is used.
// The "Allow" header with allowed request methods is set before the handler
// is called.
MethodNotAllowed http.Handler
// Function to handle panics recovered from http handlers.
// It should be used to generate a error page and return the http error code
// 500 (Internal Server Error).
// The handler can be used to keep your server from crashing because of
// unrecovered panics.
PanicHandler func(http.ResponseWriter, *http.Request, interface{})
}
// Make sure the Router conforms with the http.Handler interface
var _ http.Handler = New()
// New returns a new initialized Router.
// Path auto-correction, including trailing slashes, is enabled by default.
func New() *Router {
return &Router{
RedirectTrailingSlash: true,
RedirectFixedPath: true,
HandleMethodNotAllowed: true,
HandleOPTIONS: true,
}
}
// GET is a shortcut for router.Handle(http.MethodGet, path, handle)
func (r *Router) GET(path string, handle Handle) {
r.Handle(http.MethodGet, path, handle)
}
// HEAD is a shortcut for router.Handle(http.MethodHead, path, handle)
func (r *Router) HEAD(path string, handle Handle) {
r.Handle(http.MethodHead, path, handle)
}
// OPTIONS is a shortcut for router.Handle(http.MethodOptions, path, handle)
func (r *Router) OPTIONS(path string, handle Handle) {
r.Handle(http.MethodOptions, path, handle)
}
// POST is a shortcut for router.Handle(http.MethodPost, path, handle)
func (r *Router) POST(path string, handle Handle) {
r.Handle(http.MethodPost, path, handle)
}
// PUT is a shortcut for router.Handle(http.MethodPut, path, handle)
func (r *Router) PUT(path string, handle Handle) {
r.Handle(http.MethodPut, path, handle)
}
// PATCH is a shortcut for router.Handle(http.MethodPatch, path, handle)
func (r *Router) PATCH(path string, handle Handle) {
r.Handle(http.MethodPatch, path, handle)
}
// DELETE is a shortcut for router.Handle(http.MethodDelete, path, handle)
func (r *Router) DELETE(path string, handle Handle) {
r.Handle(http.MethodDelete, path, handle)
}
// Handle registers a new request handle with the given path and method.
//
// For GET, POST, PUT, PATCH and DELETE requests the respective shortcut
// functions can be used.
//
// This function is intended for bulk loading and to allow the usage of less
// frequently used, non-standardized or custom methods (e.g. for internal
// communication with a proxy).
func (r *Router) Handle(method, path string, handle Handle) {
if len(path) < 1 || path[0] != '/' {
panic("path must begin with '/' in path '" + path + "'")
}
if r.trees == nil {
r.trees = make(map[string]*node)
}
root := r.trees[method]
if root == nil {
root = new(node)
r.trees[method] = root
r.globalAllowed = r.allowed("*", "")
}
root.addRoute(path, handle)
}
// Handler is an adapter which allows the usage of an http.Handler as a
// request handle.
// The Params are available in the request context under ParamsKey.
func (r *Router) Handler(method, path string, handler http.Handler) {
r.Handle(method, path,
func(w http.ResponseWriter, req *http.Request, p Params) {
if len(p) > 0 {
ctx := req.Context()
ctx = context.WithValue(ctx, ParamsKey, p)
req = req.WithContext(ctx)
}
handler.ServeHTTP(w, req)
},
)
}
// HandlerFunc is an adapter which allows the usage of an http.HandlerFunc as a
// request handle.
func (r *Router) HandlerFunc(method, path string, handler http.HandlerFunc) {
r.Handler(method, path, handler)
}
// ServeFiles serves files from the given file system root.
// The path must end with "/*filepath", files are then served from the local
// path /defined/root/dir/*filepath.
// For example if root is "/etc" and *filepath is "passwd", the local file
// "/etc/passwd" would be served.
// Internally a http.FileServer is used, therefore http.NotFound is used instead
// of the Router's NotFound handler.
// To use the operating system's file system implementation,
// use http.Dir:
// router.ServeFiles("/src/*filepath", http.Dir("/var/www"))
func (r *Router) ServeFiles(path string, root http.FileSystem) {
if len(path) < 10 || path[len(path)-10:] != "/*filepath" {
panic("path must end with /*filepath in path '" + path + "'")
}
fileServer := http.FileServer(root)
r.GET(path, func(w http.ResponseWriter, req *http.Request, ps Params) {
req.URL.Path = ps.ByName("filepath")
fileServer.ServeHTTP(w, req)
})
}
func (r *Router) recv(w http.ResponseWriter, req *http.Request) {
if rcv := recover(); rcv != nil {
r.PanicHandler(w, req, rcv)
}
}
// Lookup allows the manual lookup of a method + path combo.
// This is e.g. useful to build a framework around this router.
// If the path was found, it returns the handle function and the path parameter
// values. Otherwise the third return value indicates whether a redirection to
// the same path with an extra / without the trailing slash should be performed.
func (r *Router) Lookup(method, path string) (Handle, Params, bool) {
if root := r.trees[method]; root != nil {
return root.getValue(path)
}
return nil, nil, false
}
func (r *Router) allowed(path, reqMethod string) (allow string) {
allowed := make([]string, 0, 9)
if path == "*" { // server-wide
// empty method is used for internal calls to refresh the cache
if reqMethod == "" {
for method := range r.trees {
if method == http.MethodOptions {
continue
}
// Add request method to list of allowed methods
allowed = append(allowed, method)
}
} else {
return r.globalAllowed
}
} else { // specific path
for method := range r.trees {
// Skip the requested method - we already tried this one
if method == reqMethod || method == http.MethodOptions {
continue
}
handle, _, _ := r.trees[method].getValue(path)
if handle != nil {
// Add request method to list of allowed methods
allowed = append(allowed, method)
}
}
}
if len(allowed) > 0 {
// Add request method to list of allowed methods
allowed = append(allowed, http.MethodOptions)
// Sort allowed methods.
// sort.Strings(allowed) unfortunately causes unnecessary allocations
// due to allowed being moved to the heap and interface conversion
for i, l := 1, len(allowed); i < l; i++ {
for j := i; j > 0 && allowed[j] < allowed[j-1]; j-- {
allowed[j], allowed[j-1] = allowed[j-1], allowed[j]
}
}
// return as comma separated list
return strings.Join(allowed, ", ")
}
return
}
// ServeHTTP makes the router implement the http.Handler interface.
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if r.PanicHandler != nil {
defer r.recv(w, req)
}
path := req.URL.Path
if root := r.trees[req.Method]; root != nil {
if handle, ps, tsr := root.getValue(path); handle != nil {
handle(w, req, ps)
return
} else if req.Method != http.MethodConnect && path != "/" {
code := 301 // Permanent redirect, request with GET method
if req.Method != http.MethodGet {
// Temporary redirect, request with same method
// As of Go 1.3, Go does not support status code 308.
code = 307
}
if tsr && r.RedirectTrailingSlash {
if len(path) > 1 && path[len(path)-1] == '/' {
req.URL.Path = path[:len(path)-1]
} else {
req.URL.Path = path + "/"
}
http.Redirect(w, req, req.URL.String(), code)
return
}
// Try to fix the request path
if r.RedirectFixedPath {
fixedPath, found := root.findCaseInsensitivePath(
CleanPath(path),
r.RedirectTrailingSlash,
)
if found {
req.URL.Path = string(fixedPath)
http.Redirect(w, req, req.URL.String(), code)
return
}
}
}
}
if req.Method == http.MethodOptions && r.HandleOPTIONS {
// Handle OPTIONS requests
if allow := r.allowed(path, http.MethodOptions); allow != "" {
w.Header().Set("Allow", allow)
if r.GlobalOPTIONS != nil {
r.GlobalOPTIONS.ServeHTTP(w, req)
}
return
}
} else if r.HandleMethodNotAllowed { // Handle 405
if allow := r.allowed(path, req.Method); allow != "" {
w.Header().Set("Allow", allow)
if r.MethodNotAllowed != nil {
r.MethodNotAllowed.ServeHTTP(w, req)
} else {
http.Error(w,
http.StatusText(http.StatusMethodNotAllowed),
http.StatusMethodNotAllowed,
)
}
return
}
}
// Handle 404
if r.NotFound != nil {
r.NotFound.ServeHTTP(w, req)
} else {
http.NotFound(w, req)
}
}
+666
View File
@@ -0,0 +1,666 @@
// Copyright 2013 Julien Schmidt. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file.
package httprouter
import (
"strings"
"unicode"
"unicode/utf8"
)
func min(a, b int) int {
if a <= b {
return a
}
return b
}
const maxParamCount uint8 = ^uint8(0)
func countParams(path string) uint8 {
var n uint
for i := 0; i < len(path); i++ {
if path[i] != ':' && path[i] != '*' {
continue
}
n++
}
if n >= uint(maxParamCount) {
return maxParamCount
}
return uint8(n)
}
type nodeType uint8
const (
static nodeType = iota // default
root
param
catchAll
)
type node struct {
path string
wildChild bool
nType nodeType
maxParams uint8
priority uint32
indices string
children []*node
handle Handle
}
// increments priority of the given child and reorders if necessary
func (n *node) incrementChildPrio(pos int) int {
n.children[pos].priority++
prio := n.children[pos].priority
// adjust position (move to front)
newPos := pos
for newPos > 0 && n.children[newPos-1].priority < prio {
// swap node positions
n.children[newPos-1], n.children[newPos] = n.children[newPos], n.children[newPos-1]
newPos--
}
// build new index char string
if newPos != pos {
n.indices = n.indices[:newPos] + // unchanged prefix, might be empty
n.indices[pos:pos+1] + // the index char we move
n.indices[newPos:pos] + n.indices[pos+1:] // rest without char at 'pos'
}
return newPos
}
// addRoute adds a node with the given handle to the path.
// Not concurrency-safe!
func (n *node) addRoute(path string, handle Handle) {
fullPath := path
n.priority++
numParams := countParams(path)
// non-empty tree
if len(n.path) > 0 || len(n.children) > 0 {
walk:
for {
// Update maxParams of the current node
if numParams > n.maxParams {
n.maxParams = numParams
}
// Find the longest common prefix.
// This also implies that the common prefix contains no ':' or '*'
// since the existing key can't contain those chars.
i := 0
max := min(len(path), len(n.path))
for i < max && path[i] == n.path[i] {
i++
}
// Split edge
if i < len(n.path) {
child := node{
path: n.path[i:],
wildChild: n.wildChild,
nType: static,
indices: n.indices,
children: n.children,
handle: n.handle,
priority: n.priority - 1,
}
// Update maxParams (max of all children)
for i := range child.children {
if child.children[i].maxParams > child.maxParams {
child.maxParams = child.children[i].maxParams
}
}
n.children = []*node{&child}
// []byte for proper unicode char conversion, see #65
n.indices = string([]byte{n.path[i]})
n.path = path[:i]
n.handle = nil
n.wildChild = false
}
// Make new node a child of this node
if i < len(path) {
path = path[i:]
if n.wildChild {
n = n.children[0]
n.priority++
// Update maxParams of the child node
if numParams > n.maxParams {
n.maxParams = numParams
}
numParams--
// Check if the wildcard matches
if len(path) >= len(n.path) && n.path == path[:len(n.path)] &&
// Adding a child to a catchAll is not possible
n.nType != catchAll &&
// Check for longer wildcard, e.g. :name and :names
(len(n.path) >= len(path) || path[len(n.path)] == '/') {
continue walk
} else {
// Wildcard conflict
var pathSeg string
if n.nType == catchAll {
pathSeg = path
} else {
pathSeg = strings.SplitN(path, "/", 2)[0]
}
prefix := fullPath[:strings.Index(fullPath, pathSeg)] + n.path
panic("'" + pathSeg +
"' in new path '" + fullPath +
"' conflicts with existing wildcard '" + n.path +
"' in existing prefix '" + prefix +
"'")
}
}
c := path[0]
// slash after param
if n.nType == param && c == '/' && len(n.children) == 1 {
n = n.children[0]
n.priority++
continue walk
}
// Check if a child with the next path byte exists
for i := 0; i < len(n.indices); i++ {
if c == n.indices[i] {
i = n.incrementChildPrio(i)
n = n.children[i]
continue walk
}
}
// Otherwise insert it
if c != ':' && c != '*' {
// []byte for proper unicode char conversion, see #65
n.indices += string([]byte{c})
child := &node{
maxParams: numParams,
}
n.children = append(n.children, child)
n.incrementChildPrio(len(n.indices) - 1)
n = child
}
n.insertChild(numParams, path, fullPath, handle)
return
} else if i == len(path) { // Make node a (in-path) leaf
if n.handle != nil {
panic("a handle is already registered for path '" + fullPath + "'")
}
n.handle = handle
}
return
}
} else { // Empty tree
n.insertChild(numParams, path, fullPath, handle)
n.nType = root
}
}
func (n *node) insertChild(numParams uint8, path, fullPath string, handle Handle) {
var offset int // already handled bytes of the path
// find prefix until first wildcard (beginning with ':'' or '*'')
for i, max := 0, len(path); numParams > 0; i++ {
c := path[i]
if c != ':' && c != '*' {
continue
}
// find wildcard end (either '/' or path end)
end := i + 1
for end < max && path[end] != '/' {
switch path[end] {
// the wildcard name must not contain ':' and '*'
case ':', '*':
panic("only one wildcard per path segment is allowed, has: '" +
path[i:] + "' in path '" + fullPath + "'")
default:
end++
}
}
// check if this Node existing children which would be
// unreachable if we insert the wildcard here
if len(n.children) > 0 {
panic("wildcard route '" + path[i:end] +
"' conflicts with existing children in path '" + fullPath + "'")
}
// check if the wildcard has a name
if end-i < 2 {
panic("wildcards must be named with a non-empty name in path '" + fullPath + "'")
}
if c == ':' { // param
// split path at the beginning of the wildcard
if i > 0 {
n.path = path[offset:i]
offset = i
}
child := &node{
nType: param,
maxParams: numParams,
}
n.children = []*node{child}
n.wildChild = true
n = child
n.priority++
numParams--
// if the path doesn't end with the wildcard, then there
// will be another non-wildcard subpath starting with '/'
if end < max {
n.path = path[offset:end]
offset = end
child := &node{
maxParams: numParams,
priority: 1,
}
n.children = []*node{child}
n = child
}
} else { // catchAll
if end != max || numParams > 1 {
panic("catch-all routes are only allowed at the end of the path in path '" + fullPath + "'")
}
if len(n.path) > 0 && n.path[len(n.path)-1] == '/' {
panic("catch-all conflicts with existing handle for the path segment root in path '" + fullPath + "'")
}
// currently fixed width 1 for '/'
i--
if path[i] != '/' {
panic("no / before catch-all in path '" + fullPath + "'")
}
n.path = path[offset:i]
// first node: catchAll node with empty path
child := &node{
wildChild: true,
nType: catchAll,
maxParams: 1,
}
// update maxParams of the parent node
if n.maxParams < 1 {
n.maxParams = 1
}
n.children = []*node{child}
n.indices = string(path[i])
n = child
n.priority++
// second node: node holding the variable
child = &node{
path: path[i:],
nType: catchAll,
maxParams: 1,
handle: handle,
priority: 1,
}
n.children = []*node{child}
return
}
}
// insert remaining path part and handle to the leaf
n.path = path[offset:]
n.handle = handle
}
// Returns the handle registered with the given path (key). The values of
// wildcards are saved to a map.
// If no handle can be found, a TSR (trailing slash redirect) recommendation is
// made if a handle exists with an extra (without the) trailing slash for the
// given path.
func (n *node) getValue(path string) (handle Handle, p Params, tsr bool) {
walk: // outer loop for walking the tree
for {
if len(path) > len(n.path) {
if path[:len(n.path)] == n.path {
path = path[len(n.path):]
// If this node does not have a wildcard (param or catchAll)
// child, we can just look up the next child node and continue
// to walk down the tree
if !n.wildChild {
c := path[0]
for i := 0; i < len(n.indices); i++ {
if c == n.indices[i] {
n = n.children[i]
continue walk
}
}
// Nothing found.
// We can recommend to redirect to the same URL without a
// trailing slash if a leaf exists for that path.
tsr = (path == "/" && n.handle != nil)
return
}
// handle wildcard child
n = n.children[0]
switch n.nType {
case param:
// find param end (either '/' or path end)
end := 0
for end < len(path) && path[end] != '/' {
end++
}
// save param value
if p == nil {
// lazy allocation
p = make(Params, 0, n.maxParams)
}
i := len(p)
p = p[:i+1] // expand slice within preallocated capacity
p[i].Key = n.path[1:]
p[i].Value = path[:end]
// we need to go deeper!
if end < len(path) {
if len(n.children) > 0 {
path = path[end:]
n = n.children[0]
continue walk
}
// ... but we can't
tsr = (len(path) == end+1)
return
}
if handle = n.handle; handle != nil {
return
} else if len(n.children) == 1 {
// No handle found. Check if a handle for this path + a
// trailing slash exists for TSR recommendation
n = n.children[0]
tsr = (n.path == "/" && n.handle != nil)
}
return
case catchAll:
// save param value
if p == nil {
// lazy allocation
p = make(Params, 0, n.maxParams)
}
i := len(p)
p = p[:i+1] // expand slice within preallocated capacity
p[i].Key = n.path[2:]
p[i].Value = path
handle = n.handle
return
default:
panic("invalid node type")
}
}
} else if path == n.path {
// We should have reached the node containing the handle.
// Check if this node has a handle registered.
if handle = n.handle; handle != nil {
return
}
if path == "/" && n.wildChild && n.nType != root {
tsr = true
return
}
// No handle found. Check if a handle for this path + a
// trailing slash exists for trailing slash recommendation
for i := 0; i < len(n.indices); i++ {
if n.indices[i] == '/' {
n = n.children[i]
tsr = (len(n.path) == 1 && n.handle != nil) ||
(n.nType == catchAll && n.children[0].handle != nil)
return
}
}
return
}
// Nothing found. We can recommend to redirect to the same URL with an
// extra trailing slash if a leaf exists for that path
tsr = (path == "/") ||
(len(n.path) == len(path)+1 && n.path[len(path)] == '/' &&
path == n.path[:len(n.path)-1] && n.handle != nil)
return
}
}
// Makes a case-insensitive lookup of the given path and tries to find a handler.
// It can optionally also fix trailing slashes.
// It returns the case-corrected path and a bool indicating whether the lookup
// was successful.
func (n *node) findCaseInsensitivePath(path string, fixTrailingSlash bool) (ciPath []byte, found bool) {
return n.findCaseInsensitivePathRec(
path,
make([]byte, 0, len(path)+1), // preallocate enough memory for new path
[4]byte{}, // empty rune buffer
fixTrailingSlash,
)
}
// shift bytes in array by n bytes left
func shiftNRuneBytes(rb [4]byte, n int) [4]byte {
switch n {
case 0:
return rb
case 1:
return [4]byte{rb[1], rb[2], rb[3], 0}
case 2:
return [4]byte{rb[2], rb[3]}
case 3:
return [4]byte{rb[3]}
default:
return [4]byte{}
}
}
// recursive case-insensitive lookup function used by n.findCaseInsensitivePath
func (n *node) findCaseInsensitivePathRec(path string, ciPath []byte, rb [4]byte, fixTrailingSlash bool) ([]byte, bool) {
npLen := len(n.path)
walk: // outer loop for walking the tree
for len(path) >= npLen && (npLen == 0 || strings.EqualFold(path[1:npLen], n.path[1:])) {
// add common prefix to result
oldPath := path
path = path[npLen:]
ciPath = append(ciPath, n.path...)
if len(path) > 0 {
// If this node does not have a wildcard (param or catchAll) child,
// we can just look up the next child node and continue to walk down
// the tree
if !n.wildChild {
// skip rune bytes already processed
rb = shiftNRuneBytes(rb, npLen)
if rb[0] != 0 {
// old rune not finished
for i := 0; i < len(n.indices); i++ {
if n.indices[i] == rb[0] {
// continue with child node
n = n.children[i]
npLen = len(n.path)
continue walk
}
}
} else {
// process a new rune
var rv rune
// find rune start
// runes are up to 4 byte long,
// -4 would definitely be another rune
var off int
for max := min(npLen, 3); off < max; off++ {
if i := npLen - off; utf8.RuneStart(oldPath[i]) {
// read rune from cached path
rv, _ = utf8.DecodeRuneInString(oldPath[i:])
break
}
}
// calculate lowercase bytes of current rune
lo := unicode.ToLower(rv)
utf8.EncodeRune(rb[:], lo)
// skip already processed bytes
rb = shiftNRuneBytes(rb, off)
for i := 0; i < len(n.indices); i++ {
// lowercase matches
if n.indices[i] == rb[0] {
// must use a recursive approach since both the
// uppercase byte and the lowercase byte might exist
// as an index
if out, found := n.children[i].findCaseInsensitivePathRec(
path, ciPath, rb, fixTrailingSlash,
); found {
return out, true
}
break
}
}
// if we found no match, the same for the uppercase rune,
// if it differs
if up := unicode.ToUpper(rv); up != lo {
utf8.EncodeRune(rb[:], up)
rb = shiftNRuneBytes(rb, off)
for i, c := 0, rb[0]; i < len(n.indices); i++ {
// uppercase matches
if n.indices[i] == c {
// continue with child node
n = n.children[i]
npLen = len(n.path)
continue walk
}
}
}
}
// Nothing found. We can recommend to redirect to the same URL
// without a trailing slash if a leaf exists for that path
return ciPath, (fixTrailingSlash && path == "/" && n.handle != nil)
}
n = n.children[0]
switch n.nType {
case param:
// find param end (either '/' or path end)
k := 0
for k < len(path) && path[k] != '/' {
k++
}
// add param value to case insensitive path
ciPath = append(ciPath, path[:k]...)
// we need to go deeper!
if k < len(path) {
if len(n.children) > 0 {
// continue with child node
n = n.children[0]
npLen = len(n.path)
path = path[k:]
continue
}
// ... but we can't
if fixTrailingSlash && len(path) == k+1 {
return ciPath, true
}
return ciPath, false
}
if n.handle != nil {
return ciPath, true
} else if fixTrailingSlash && len(n.children) == 1 {
// No handle found. Check if a handle for this path + a
// trailing slash exists
n = n.children[0]
if n.path == "/" && n.handle != nil {
return append(ciPath, '/'), true
}
}
return ciPath, false
case catchAll:
return append(ciPath, path...), true
default:
panic("invalid node type")
}
} else {
// We should have reached the node containing the handle.
// Check if this node has a handle registered.
if n.handle != nil {
return ciPath, true
}
// No handle found.
// Try to fix the path by adding a trailing slash
if fixTrailingSlash {
for i := 0; i < len(n.indices); i++ {
if n.indices[i] == '/' {
n = n.children[i]
if (len(n.path) == 1 && n.handle != nil) ||
(n.nType == catchAll && n.children[0].handle != nil) {
return append(ciPath, '/'), true
}
return ciPath, false
}
}
}
return ciPath, false
}
}
// Nothing found.
// Try to fix the path by adding / removing a trailing slash
if fixTrailingSlash {
if path == "/" {
return ciPath, true
}
if len(path)+1 == npLen && n.path[len(path)] == '/' &&
strings.EqualFold(path[1:], n.path[1:len(path)]) && n.handle != nil {
return append(ciPath, n.path...), true
}
}
return ciPath, false
}
+81
View File
@@ -0,0 +1,81 @@
# Package `http`
Пакет `http` предоставляет инструменты для создания и управления HTTP-сервером с поддержкой middleware, обработки
запросов и гибкой настройки. Интегрируется с системой логирования и обработки ошибок.
## Types
### Server
Структура Server управляет жизненным циклом HTTP-сервера, включая запуск, остановку и динамическое обновление
обработчиков.
**Methods:**
#### `NewServer(logger log.Logger, opts ...ServerOption) *Server`
Конструктор сервера. Дополнительно принимает опции:
- `WithServer(server *http.Server) ServerOption` – использование объекта предварительно настроенного HTTP-сервера из
стандартной библиотеки `net/http`.
#### `(s *Server) Upgrade(handler http.Handler)`
Атомарно заменить текущий обработчик запросов на новый.
#### `(s *Server) ListenAndServe(address string) error`
Запустить сервер на указанном адресе.
#### `(s *Server) Serve(listener net.Listener) error`
Запустить сервер на существующем listener.
#### `(s *Server) Shutdown(ctx context.Context) error`
Остановить сервер, завершив все активные соединения.
## Usage
### Default usage flow
```go
package main
import (
"context"
"log"
"net/http"
http2 "github.com/txix-open/isp-kit/http"
log2 "github.com/txix-open/isp-kit/log"
"github.com/txix-open/isp-kit/shutdown"
)
func main() {
logger, err := log2.New()
if err != nil {
log.Fatal(err)
}
srv := http2.NewServer(logger)
mux := http.NewServeMux()
mux.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("hello world!!"))
})
srv.Upgrade(mux)
shutdown.On(func() { /* waiting for SIGINT & SIGTERM signals */
log.Println("shutting down...")
_ = srv.Shutdown(context.Background())
log.Println("shutdown completed")
})
err = srv.ListenAndServe(":8080")
if err != nil {
log.Fatal(err)
}
}
```
+95
View File
@@ -0,0 +1,95 @@
# Package `apierrors`
Пакет `apierrors` предоставляет инструменты для создания и управления структурированными ошибками HTTP-API.
Ошибки включают код, сообщение, детали и уровень логирования, а также автоматически сериализуются в JSON для ответов
клиентам.
## Types
### Error
Структура для представления ошибки API. Реализует интерфейс `error`.
**Methods:**
#### `NewInternalServiceError(err error) Error`
Создает ошибку для внутренних сбоев сервера. Возвращает ошибку с HTTP-статусом 500, бизнесовым кодом 900 и уровнем
логирования error.
#### `NewBusinessError(errorCode int, errorMessage string, err error) Error`
Создает бизнес-ошибку (например, невалидные данные от клиента). Возвращает ошибку с HTTP-статусом 400, указанным
бизнесовым кодом и уровнем логирования warn.
#### `New(httpStatusCode int, errorCode int, errorMessage string, err error) Error`
Создает кастомную ошибку с полным контролем параметров.
#### `(e Error) Error() string`
Получить строковое представление ошибки.
#### `(e Error) WriteError(w http.ResponseWriter) error`
Сериализует ошибку в JSON и записывает в `http.ResponseWriter`.
#### `(e Error) WithDetails(details map[string]any) Error`
Добавить детали информации об ошибке.
#### `(e Error) WithLogLevel(level log.Level) Error`
Изменить уровень логирования ошибки.
#### `(e Error) LogLevel() log.Level`
Получить текущий уровень логирования ошибки
## Usage
### Default usage flow
```go
package main
import (
"context"
"errors"
"github.com/txix-open/isp-kit/http/apierrors"
)
type User struct {
Id string
Name string
}
var (
ErrUserNotFound = errors.New("user not found")
ErrUserNotFoundCode = 700
)
type userService interface {
GetUserById(ctx context.Context, id string) (*User, error)
}
type userController struct {
svc userService
}
func (c userController) GetUser(ctx context.Context, userId string) (*User, error) {
result, err := c.svc.GetUserById(ctx, userId)
switch {
case errors.Is(err, ErrUserNotFound):
/* user isn't found so we have to send back specific error code */
return nil, apierrors.NewBusinessError(ErrUserNotFoundCode, ErrUserNotFound.Error(), err)
case err != nil:
/* got some internal error */
return nil, apierrors.NewInternalServiceError(err)
default:
return result, nil
}
}
```
+93
View File
@@ -0,0 +1,93 @@
// Package apierrors provides HTTP error handling with structured error responses.
// It supports business and internal errors with customizable HTTP status codes,
// error codes, and logging levels.
package apierrors
import (
"fmt"
"net/http"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/json"
"github.com/txix-open/isp-kit/log"
)
const (
// ErrCodeInternal is the default error code for internal service errors.
ErrCodeInternal = 900
)
// Error represents a structured HTTP error with an error code, message, and optional details.
// It supports custom HTTP status codes, logging levels, and error chaining.
type Error struct {
ErrorCode int
ErrorMessage string
Details map[string]any `json:",omitempty"`
httpStatusCode int
cause error
level log.Level
}
// NewInternalServiceError creates a new internal service error with HTTP 500 status code.
// It logs at Error level and wraps the provided cause error.
func NewInternalServiceError(err error) Error {
return New(http.StatusInternalServerError, ErrCodeInternal, "internal service error", err).WithLogLevel(log.ErrorLevel)
}
// NewBusinessError creates a new business error with HTTP 400 status code.
// It logs at Warn level and is used for client-side validation or business logic errors.
func NewBusinessError(errorCode int, errorMessage string, err error) Error {
return New(http.StatusBadRequest, errorCode, errorMessage, err).WithLogLevel(log.WarnLevel)
}
// New creates a new Error with the specified HTTP status code, error code, message, and cause.
// The default log level is ErrorLevel.
func New(
httpStatusCode int,
errorCode int,
errorMessage string,
err error,
) Error {
return Error{
ErrorCode: errorCode,
ErrorMessage: errorMessage,
httpStatusCode: httpStatusCode,
cause: err,
level: log.ErrorLevel,
}
}
// Error returns a formatted string representation of the error.
func (e Error) Error() string {
return fmt.Sprintf("errorCode: %d, errorMessage: %s, cause: %v", e.ErrorCode, e.ErrorMessage, e.cause)
}
// WriteError writes the error as a JSON response to the http.ResponseWriter.
// It sets the Content-Type header to application/json and the appropriate HTTP status code.
func (e Error) WriteError(w http.ResponseWriter) error {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(e.httpStatusCode)
err := json.NewEncoder(w).Encode(e)
if err != nil {
return errors.WithMessage(err, "json encode error")
}
return nil
}
// WithDetails adds additional context details to the error.
func (e Error) WithDetails(details map[string]any) Error {
e.Details = details
return e
}
// WithLogLevel sets the logging level for this error.
func (e Error) WithLogLevel(level log.Level) Error {
e.level = level
return e
}
// LogLevel returns the logging level associated with this error.
func (e Error) LogLevel() log.Level {
return e.level
}
+16
View File
@@ -0,0 +1,16 @@
// Package http provides core HTTP server functionality and types for building REST and SOAP services.
// It includes a server implementation, handler wrapper, and middleware support for request processing.
package http
import (
"context"
"net/http"
)
// HandlerFunc is the signature for HTTP handlers that process requests in a context-aware manner.
// Handlers should return an error to indicate processing failure.
type HandlerFunc func(ctx context.Context, w http.ResponseWriter, r *http.Request) error
// Middleware is a function that wraps a HandlerFunc to add cross-cutting concerns
// such as logging, authentication, or metrics collection.
type Middleware func(next HandlerFunc) HandlerFunc
+257
View File
@@ -0,0 +1,257 @@
# Package `endpoint`
Пакет `endpoint` предоставляет инструменты для создания HTTP-обработчиков с поддержкой middleware, валидации данных,
логирования и метрик. Упрощает разработку API, автоматизируя рутинные задачи.
## Types
### Wrapper
Структура для создания оберток вокруг обработчиков. Объединяет:
- Параметры функции (контекст, запрос, тело и т.д.).
- Middleware (логирование, метрики, трейсинг).
- Валидацию и сериализацию данных.
**Methods:**
#### `NewWrapper(paramMappers []ParamMapper, bodyExtractor RequestBodyExtractor, bodyMapper ResponseBodyMapper, logger log.Logger) Wrapper`
Конструктор обертки с указанными параметрами.
#### `(m Wrapper) Endpoint(f any) http.HandlerFunc`
Преобразовать функцию-обработчик в HTTP-обработчик.
#### `(m Wrapper) WithMiddlewares(middlewares ...http2.Middleware) Wrapper`
Билдер-метод для добавления middleware в обертку.
### JsonRequestExtractor
Извлекает JSON из тела запроса и валидирует его с помощью объекта, реализующего интерфейс `Validator`.
**Methods:**
####
`(j JsonRequestExtractor) Extract(ctx context.Context, reader io.Reader, reqBodyType reflect.Type) (reflect.Value, error)`
Десериализовать JSON и проверить данные через `Validator`.
### JsonResponseMapper
Сериализует ответ в JSON и добавляет заголовки.
**Methods:**
#### `(j JsonResponseMapper) Map(ctx context.Context, result any, w http.ResponseWriter) error`
Упаковка результата в JSON-ответ.
### Caller
Структура `Caller` предоставляет механизм для вызова функций-обработчиков HTTP-запросов, автоматически преобразуя
параметры запроса в аргументы функции. Интегрируется с валидацией, извлечением данных и middleware.
**Methods:**
####
`NewCaller(f any, bodyExtractor RequestBodyExtractor, bodyMapper ResponseBodyMapper, paramMappers map[string]ParamMapper) (*Caller, error)`
Создает экземпляр `Caller` для функции-обработчика.
#### `(h *Caller) Handle(ctx context.Context, w http.ResponseWriter, r *http.Request) error`
Вызывает функцию-обработчик, передавая ей аргументы, извлеченные из запроса.
## Middlewares
### `MaxRequestBodySize`
Ограничивает размер тела запроса (по умолчанию 64 МБ).
### `RequestId`
Добавляет в контекст requestId, который берет из заголовка x-request-id. Генерирует новый, если не находит.
### `DecodeRequest`
Декодирует запрос при помощи переданного codec, если заголовок `Content-Encoding` совпадает с типом codec.
### `LogMiddleware`
Логирует данные запросов и ответов.
### `Metrics`
Собирает метрики: время выполнения, статус-коды, размеры тел.
### `Tracing`
Интеграция с трейсингом (OpenTelemetry).
### `EncodeResponse`
Кодирует ответ при помощи переданного codec, если заголовок `Accept-Encoding` содержит строку с типом codec (пример значения заголовка `"zstd, identity"`) и размер ответа больше переданного threshold'а, по умолчанию 128 КБ (параметр в байтах).
### `ErrorHandler`
Перехватывает и обрабатывает ошибки. Ошибки типа `HttpError` возвращают структурированный ответ.
Остальные ошибки логируются и возвращаются как 500 Internal Server Error.
### `Recovery`
Предотвращает падение сервера при панике в обработчике, преобразуя ее в ошибку.
## Functions
#### `DefaultWrapper(logger log.Logger, logMiddleware LogMiddleware, restMiddlewares ...http.Middleware) Wrapper`
Создает предварительно настроенную обертку (`Wrapper`) для HTTP-обработчиков с middleware и параметрами.
Упрощает создание эндпоинтов, включая валидацию, логирование, метрики и обработку ошибок "из коробки".
Список Middleware:
- `MaxRequestBodySize`
- `RequestId`
- `LogMiddleware`
- `Metrics`
- `Tracing`
- `ErrorHandler`
- `Recovery`
#### `DefaultCodecWrapper(logger log.Logger, logMiddleware LogMiddleware, restMiddlewares ...http.Middleware) Wrapper`
Создает предварительно настроенную обертку (`Wrapper`) для HTTP-обработчиков с middleware и параметрами.
Упрощает создание эндпоинтов, включая валидацию, логирование, метрики и обработку ошибок "из коробки".
Список Middleware:
- `MaxRequestBodySize`
- `RequestId`
- `DecodeRequest`
- `LogMiddleware`
- `Metrics`
- `Tracing`
- `EncodeResponse`
- `ErrorHandler`
- `Recovery`
## Usage
### Default usage flow
```go
package main
import (
"context"
"log"
"github.com/txix-open/isp-kit/http"
"github.com/txix-open/isp-kit/http/endpoint"
"github.com/txix-open/isp-kit/http/endpoint/httplog"
"github.com/txix-open/isp-kit/http/router"
log2 "github.com/txix-open/isp-kit/log"
"github.com/txix-open/isp-kit/shutdown"
)
type userRequest struct {
Name string
}
type userResponse struct {
Id int
}
func foo(ctx context.Context, req userRequest) (userResponse, error) {
/* put here some business logic */
return userResponse{Id: 88}, nil
}
func main() {
logger, err := log2.New()
if err != nil {
log.Fatal(err)
}
srv := http.NewServer(logger)
wrapper := endpoint.DefaultWrapper(logger, httplog.Log(logger, true))
r := router.New()
r.POST("/foo", wrapper.Endpoint(foo))
srv.Upgrade(r)
shutdown.On(func() { /* waiting for SIGINT & SIGTERM signals */
log.Println("shutting down...")
_ = srv.Shutdown(context.Background())
log.Println("shutdown completed")
})
err = srv.ListenAndServe(":8080")
if err != nil {
log.Fatal(err)
}
}
```
### Codec usage flow
```go
package main
import (
"context"
"log"
"github.com/txix-open/isp-kit/http"
"github.com/txix-open/isp-kit/http/endpoint"
"github.com/txix-open/isp-kit/http/endpoint/httplog"
"github.com/txix-open/isp-kit/http/router"
log2 "github.com/txix-open/isp-kit/log"
"github.com/txix-open/isp-kit/shutdown"
)
type userRequest struct {
Name string
}
type userResponse struct {
Id int
}
func foo(ctx context.Context, req userRequest) (userResponse, error) {
/* put here some business logic */
return userResponse{Id: 88}, nil
}
func main() {
logger, err := log2.New()
if err != nil {
log.Fatal(err)
}
srv := http.NewServer(logger)
wrapper := endpoint.DefaultCodecWrapper(logger, httplog.Log(logger, true))
r := router.New()
r.POST("/foo", wrapper.Endpoint(foo))
srv.Upgrade(r)
shutdown.On(func() { /* waiting for SIGINT & SIGTERM signals */
log.Println("shutting down...")
_ = srv.Shutdown(context.Background())
log.Println("shutdown completed")
})
err = srv.ListenAndServe(":8080")
if err != nil {
log.Fatal(err)
}
}
```
+88
View File
@@ -0,0 +1,88 @@
# Package `buffer`
Пакет `buffer` предоставляет инструменты для буферизации HTTP-запросов и ответов. Используется в middleware для
логирования, метрик и других задач, требующих доступа к телам запросов и ответов без их модификации.
## Types
### Buffer
Структура для перехвата и буферизации данных HTTP-ответа. Реализует интерфейс `http.ResponseWriter`.
**Methods:**
#### `New() *Buffer`
Конструктор буфера. Инициализирует внутренние буферы для тела запроса и ответа.
#### `(m *Buffer) Reset(w http.ResponseWriter)`
Сбрасывает состояние буфера и привязывает его к новому `http.ResponseWriter`.
#### `(m *Buffer) Write(b []byte) (int, error)`
Перехватывает данные, записываемые в ответ, и сохраняет их в буфер.
#### `(m *Buffer) WriteHeader(statusCode int)`
Фиксирует статус-код ответа.
#### `(m *Buffer) ResponseBody() []byte`
Возвращает тело ответа в виде байтов из буфера.
#### `(m *Buffer) RequestBody() []byte`
Возвращает тело запроса в виде байтов из буфера.
#### `(m *Buffer) ReadRequestBody(r io.Reader) error`
Читает тело запроса и сохраняет его в буфер.
#### `(m *Buffer) StatusCode() int`
Возвращает статус-код ответа. Если статус-код не был еще записан, вернется 200 OK.
## Functions
#### `Acquire(w http.ResponseWriter) *Buffer`
Берет буфер из пула и инициализирует его для работы с указанным `http.ResponseWriter`.
#### `Release(w *Buffer)`
Возвращает буфер в пул для повторного использования.
## Usage
### Default usage flow
```go
package main
import (
"log"
"net/http"
"github.com/txix-open/isp-kit/http/endpoint/buffer"
)
func LoggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
/* get buffer from pool */
buf := buffer.Acquire(w)
defer buffer.Release(buf)
/* read request body */
_ = buf.ReadRequestBody(r.Body)
r.Body = buffer.NewRequestBody(buf.RequestBody())
next.ServeHTTP(buf, r)
/* log response body */
responseBody := buf.ResponseBody()
log.Printf("Response: %s\n", responseBody)
})
}
```
+88
View File
@@ -0,0 +1,88 @@
// Package buffer provides a ResponseWriter wrapper that buffers request and response bodies.
// It is used for logging and metrics collection in HTTP middleware.
package buffer
import (
"bytes"
"io"
"net/http"
)
const (
// defaultBufferSize is the initial buffer size in bytes.
defaultBufferSize = 1024
)
// Buffer wraps http.ResponseWriter to capture request and response bodies.
// It is commonly used in middleware for logging and metrics collection.
type Buffer struct {
http.ResponseWriter
requestBuffer *bytes.Buffer
responseBuffer *bytes.Buffer
statusCode int
}
// New creates a new Buffer with initialized request and response buffers.
func New() *Buffer {
return &Buffer{
requestBuffer: bytes.NewBuffer(make([]byte, defaultBufferSize)),
responseBuffer: bytes.NewBuffer(make([]byte, defaultBufferSize)),
}
}
// Reset reinitializes the buffer with a new ResponseWriter and clears internal state.
// It should be called before reusing a pooled Buffer.
func (m *Buffer) Reset(w http.ResponseWriter) {
m.ResponseWriter = w
m.statusCode = 0
m.responseBuffer.Reset()
m.requestBuffer.Reset()
}
// Write writes data to both the underlying ResponseWriter and the response buffer.
// It returns the number of bytes written and any error encountered.
func (m *Buffer) Write(b []byte) (int, error) {
n, err := m.ResponseWriter.Write(b)
if err != nil {
return n, err
}
n, err = m.responseBuffer.Write(b)
if err != nil {
return 0, err
}
return n, nil
}
// WriteHeader captures the status code and delegates to the underlying ResponseWriter.
func (m *Buffer) WriteHeader(statusCode int) {
m.statusCode = statusCode
m.ResponseWriter.WriteHeader(statusCode)
}
// ResponseBody returns the captured response body as a byte slice.
func (m *Buffer) ResponseBody() []byte {
return m.responseBuffer.Bytes()
}
// RequestBody returns the captured request body as a byte slice.
func (m *Buffer) RequestBody() []byte {
return m.requestBuffer.Bytes()
}
// ReadRequestBody reads the entire request body into the buffer.
// It returns an error if the read operation fails.
func (m *Buffer) ReadRequestBody(r io.Reader) error {
_, err := io.Copy(m.requestBuffer, r)
return err
}
// StatusCode returns the captured status code, or http.StatusOK if not set.
func (m *Buffer) StatusCode() int {
if m.statusCode == 0 {
return http.StatusOK
}
return m.statusCode
}
+33
View File
@@ -0,0 +1,33 @@
package buffer
import (
"net/http"
"sync"
)
// pool is a global sync.Pool for reusing Buffer instances.
// It reduces memory allocation overhead by pooling Buffer objects.
var pool = sync.Pool{
New: func() any {
return New()
},
}
// Acquire retrieves a Buffer from the pool and initializes it with the given ResponseWriter.
// It is safe for concurrent use and should be paired with Release.
func Acquire(w http.ResponseWriter) *Buffer {
var buffer *Buffer
var ok bool
buffer, ok = pool.Get().(*Buffer)
if !ok {
buffer = New()
}
buffer.Reset(w)
return buffer
}
// Release returns a Buffer to the pool for reuse.
// It should be called after the Buffer is no longer needed.
func Release(w *Buffer) {
pool.Put(w)
}
@@ -0,0 +1,29 @@
package buffer
import (
"bytes"
)
// RequestBody wraps a bytes.Buffer to provide an io.ReadCloser for request body replay.
// It is used when the request body needs to be read multiple times (e.g., for logging).
type RequestBody struct {
body *bytes.Buffer
}
// NewRequestBody creates a new RequestBody from a byte slice.
func NewRequestBody(body []byte) RequestBody {
return RequestBody{
body: bytes.NewBuffer(body),
}
}
// Read reads data from the underlying buffer into p.
// It returns the number of bytes read and any error encountered.
func (r RequestBody) Read(p []byte) (n int, err error) {
return r.body.Read(p)
}
// Close is a no-op to satisfy the io.ReadCloser interface.
func (r RequestBody) Close() error {
return nil
}
+123
View File
@@ -0,0 +1,123 @@
package endpoint
import (
"context"
"net/http"
"reflect"
"github.com/txix-open/isp-kit/errors"
)
// param represents a function parameter that can be built from the request context.
type param struct {
index int
builder ParamBuilder
}
// Caller uses reflection to wrap arbitrary functions as HTTP handlers.
// It automatically extracts request body, builds parameters from the context,
// and maps return values to the response.
type Caller struct {
bodyExtractor RequestBodyExtractor
bodyMapper ResponseBodyMapper
handler reflect.Value
paramsCount int
params []param
reqBodyIndex int
reqBodyType reflect.Type
hasResult bool
hasError bool
errorIndex int
}
// NewCaller creates a new Caller that wraps the provided function.
// It analyzes the function signature and configures parameter extraction and result mapping.
// Returns an error if the provided value is not a function or has invalid parameter types.
func NewCaller(
f any,
bodyExtractor RequestBodyExtractor,
bodyMapper ResponseBodyMapper,
paramMappers map[string]ParamMapper,
) (*Caller, error) {
rt := reflect.TypeOf(f)
if rt.Kind() != reflect.Func {
return nil, errors.New("function expected")
}
paramsCount := rt.NumIn()
reqBodyIndex := -1
handler := reflect.ValueOf(f)
var reqBodyType reflect.Type
params := make([]param, 0, paramsCount)
for i := range paramsCount {
p := rt.In(i)
paramType := p.String()
mapper, ok := paramMappers[paramType]
if !ok { // maybe it's a request body
if reqBodyIndex != -1 {
return nil, errors.Errorf("param mapper not found for type %s", paramType)
}
reqBodyIndex = i
reqBodyType = p
continue
}
// it's a simple param
params = append(params, param{index: i, builder: mapper.Builder})
}
numOut := rt.NumOut()
hasResult := numOut > 0 && rt.Out(0) != reflect.TypeFor[*error]().Elem()
hasError := numOut > 0 && rt.Out(numOut-1) == reflect.TypeFor[*error]().Elem()
return &Caller{
bodyExtractor: bodyExtractor,
bodyMapper: bodyMapper,
handler: handler,
paramsCount: paramsCount,
params: params,
reqBodyIndex: reqBodyIndex,
reqBodyType: reqBodyType,
hasResult: hasResult,
hasError: hasError,
errorIndex: numOut - 1,
}, nil
}
// Handle invokes the wrapped function with extracted parameters and maps the result.
// It returns an error if parameter extraction fails or the function returns an error.
func (h *Caller) Handle(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
args := make([]reflect.Value, h.paramsCount)
if h.reqBodyIndex != -1 {
value, err := h.bodyExtractor.Extract(ctx, r.Body, h.reqBodyType)
if err != nil {
return err
}
args[h.reqBodyIndex] = value
}
for _, p := range h.params {
value, err := p.builder(ctx, w, r)
if err != nil {
return err
}
args[p.index] = reflect.ValueOf(value)
}
out := h.handler.Call(args)
if h.hasError && !out[h.errorIndex].IsNil() {
return out[h.errorIndex].Interface().(error) // nolint:forcetypeassert
}
if h.hasResult {
return h.bodyMapper.Map(ctx, out[0].Interface(), w)
}
return nil
}
+201
View File
@@ -0,0 +1,201 @@
package endpoint
import (
"bufio"
"bytes"
"context"
"io"
"net"
"net/http"
"strings"
"github.com/txix-open/isp-kit/codec"
"github.com/txix-open/isp-kit/errors"
http2 "github.com/txix-open/isp-kit/http"
)
type DecodeCodec interface {
Type() string
Decode(r io.ReadCloser) (io.ReadCloser, error)
}
const (
defaultEncodeThreshold = codec.DefaultEncodeThreshold
)
// DecodeRequest returns middleware that transparently handles encoded requests.
//
// If Content-Encoding matches codec, request body is decoded.
//
// Important:
// - Should be placed before logging middleware if logs must see decoded data.
func DecodeRequest(codec DecodeCodec) http2.Middleware {
return func(next http2.HandlerFunc) http2.HandlerFunc {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
if r.Header.Get("Content-Encoding") == codec.Type() {
decoded, err := codec.Decode(r.Body)
if err != nil {
return err
}
r.Body = decoded
r.Header.Del("Content-Encoding")
r.Header.Del("Content-Length")
}
return next(ctx, w, r)
}
}
}
type EncodeCodec interface {
Type() string
Encode(w io.Writer) (io.WriteCloser, error)
}
// EncodeResponse returns middleware that transparently handles response encoding.
//
// If client supports Accept-Encoding and response body size > encodeThresholdBytes,
// the response is encoded using codec.
//
// The middleware finalizes the response after the handler returns. It may
// implicitly call WriteHeader(http.StatusOK) and flush buffered response data
// even if the handler never calls Write or WriteHeader.
//
// Important:
// - Should be placed before logging middleware if logs must see plain data.
func EncodeResponse(codec EncodeCodec, encodeThresholdBytes int) http2.Middleware {
return func(next http2.HandlerFunc) http2.HandlerFunc {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
if !acceptsEncoding(r.Header.Get("Accept-Encoding"), codec.Type()) {
return next(ctx, w, r)
}
cw := newEncoderWriter(w, codec, encodeThresholdBytes)
err := next(ctx, cw, r)
closeErr := cw.Close()
if err != nil {
return err
}
return closeErr
}
}
}
type encoderWriter struct {
http.ResponseWriter
codec EncodeCodec
buffer bytes.Buffer
encodeThreshold int
writer io.WriteCloser
status int
}
func newEncoderWriter(w http.ResponseWriter, codec EncodeCodec, encodeThreshold int) *encoderWriter {
return &encoderWriter{
ResponseWriter: w,
codec: codec,
encodeThreshold: encodeThreshold,
}
}
func (w *encoderWriter) WriteHeader(code int) {
if w.status != 0 {
return
}
w.status = code
}
func (w *encoderWriter) Write(b []byte) (int, error) {
if w.writer != nil {
return w.writer.Write(b)
}
// fast path: big first write
if w.buffer.Len() == 0 && len(b) > w.encodeThreshold {
return w.startEncoding(b)
}
n, err := w.buffer.Write(b)
if err != nil {
return n, err
}
if w.buffer.Len() > w.encodeThreshold {
data := append([]byte(nil), w.buffer.Bytes()...)
w.buffer.Reset()
return w.startEncoding(data)
}
return n, nil
}
func (w *encoderWriter) Close() error {
if w.writer != nil {
return w.writer.Close()
}
status := w.status
if status == 0 {
status = http.StatusOK
}
w.ResponseWriter.WriteHeader(status)
_, err := w.ResponseWriter.Write(w.buffer.Bytes())
return err
}
// Hijack implements http.Hijacker.
//
// Hijacking is only allowed before the response has started (no buffered or
// encoded data). Once any response data has been written or encoding has been
// triggered, hijacking is disallowed to prevent losing buffered state and to
// preserve response integrity.
func (w *encoderWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
if w.writer != nil || w.buffer.Len() > 0 || w.status != 0 {
return nil, nil, errors.New("encoderWriter: hijack not allowed after response started")
}
upstream, ok := w.ResponseWriter.(http.Hijacker)
if !ok {
return nil, nil, errors.New("encoderWriter: upstream writer doesn't implement Hijack")
}
return upstream.Hijack()
}
func (w *encoderWriter) startEncoding(b []byte) (int, error) {
writer, err := w.codec.Encode(w.ResponseWriter)
if err != nil {
return 0, err
}
w.writer = writer
h := w.Header()
h.Set("Content-Encoding", w.codec.Type())
h.Add("Vary", "Accept-Encoding")
h.Del("Content-Length")
status := w.status
if status == 0 {
status = http.StatusOK
}
w.ResponseWriter.WriteHeader(status)
return w.writer.Write(b)
}
func acceptsEncoding(header, encoding string) bool {
for part := range strings.SplitSeq(header, ",") {
if strings.TrimSpace(part) == encoding {
return true
}
}
return false
}
+74
View File
@@ -0,0 +1,74 @@
package endpoint
import (
"github.com/txix-open/isp-kit/codec"
"github.com/txix-open/isp-kit/http"
"github.com/txix-open/isp-kit/log"
"github.com/txix-open/isp-kit/metrics"
"github.com/txix-open/isp-kit/metrics/http_metrics"
"github.com/txix-open/isp-kit/observability/tracing/http/server_tracing"
"github.com/txix-open/isp-kit/validator"
)
// DefaultWrapper creates a pre-configured Wrapper with common middleware and settings.
// It includes request logging, metrics collection, tracing, error handling, and recovery.
// The default maximum request body size is 64MB.
func DefaultWrapper(logger log.Logger, logMiddleware LogMiddleware, restMiddlewares ...http.Middleware) Wrapper {
paramMappers := []ParamMapper{
ContextParam(),
ResponseWriterParam(),
RequestParam(),
}
middlewares := append(
[]http.Middleware{
MaxRequestBodySize(defaultMaxRequestBodySize),
RequestId(),
http.Middleware(logMiddleware),
Metrics(http_metrics.NewServerStorage(metrics.DefaultRegistry)),
server_tracing.NewConfig().Middleware(),
ErrorHandler(logger),
Recovery(),
},
restMiddlewares...,
)
return NewWrapper(
paramMappers,
JsonRequestExtractor{Validator: validator.Default},
JsonResponseMapper{},
logger,
).WithMiddlewares(middlewares...)
}
// DefaultCodecWrapper creates a pre-configured Wrapper with common middleware and settings.
// It includes request logging, encode response, decode request, metrics collection, tracing, error handling, and recovery.
// The default maximum request body size is 64MB.
func DefaultCodecWrapper(logger log.Logger, logMiddleware LogMiddleware, restMiddlewares ...http.Middleware) Wrapper {
paramMappers := []ParamMapper{
ContextParam(),
ResponseWriterParam(),
RequestParam(),
}
codec := codec.Default
middlewares := append(
[]http.Middleware{
MaxRequestBodySize(defaultMaxRequestBodySize),
RequestId(),
DecodeRequest(codec),
Metrics(http_metrics.NewServerStorage(metrics.DefaultRegistry)),
server_tracing.NewConfig().Middleware(),
EncodeResponse(codec, defaultEncodeThreshold),
http.Middleware(logMiddleware),
ErrorHandler(logger),
Recovery(),
},
restMiddlewares...,
)
return NewWrapper(
paramMappers,
JsonRequestExtractor{Validator: validator.Default},
JsonResponseMapper{},
logger,
).WithMiddlewares(middlewares...)
}
+89
View File
@@ -0,0 +1,89 @@
# Package `httplog`
Пакет `httplog` предоставляет middleware для логирования HTTP-запросов и ответов. Поддерживает гибкую настройку: выбор
типов контента для логирования тела, управление детализацией и интеграцию с буферизацией данных.
## Functions
#### `Log(logger log.Logger, logBody bool) endpoint.LogMiddleware`
Создает middleware с базовыми настройками:
- Логирует тело запроса/ответа, если `logBody = true`.
- По умолчанию логирует только для `application/json` и `text/xml`.
#### `CombinedLog(logger log.Logger, logBody bool) endpoint.LogMiddleware`
Создает middleware с базовыми настройками:
- Логирует тело запроса/ответа, если `logBody = true`.
- По умолчанию логирует только для `application/json` и `text/xml`.
- Собирает запрос и ответ в 1 лог.
#### `LogWithOptions(logger log.Logger, opts ...Option) endpoint.LogMiddleware`
Создает middleware с кастомными настройками через опции:
- `WithContentTypes(logBodyContentTypes []string) Option` – Задает типы контента, для которых логируется тело (например,
`application/json`).
- `WithLogBody(logBody bool) Option` – Включает/отключает логирование тела запроса и ответа.
- `WithLogResponseBody(logResponseBody bool) Option` – Включает/отключает логирование тела ответа.
- `WithLogRequestBody(logRequestBody bool) Option` – Включает/отключает логирование тела запроса.
- `WithCombinedLog(enable bool) Option` – Включает/отключает сборку запроса/ответа в 1 лог.
## Usage
### Default log middleware
```go
package main
import (
"log"
"github.com/txix-open/isp-kit/http/endpoint"
"github.com/txix-open/isp-kit/http/endpoint/httplog"
log2 "github.com/txix-open/isp-kit/log"
)
func main() {
logger, err := log2.New()
if err != nil {
log.Fatal(err)
}
/* create wrapper with default logging middleware */
wrapper := endpoint.DefaultWrapper(logger, httplog.Log(logger, true))
}
```
### Customize log middleware
```go
package main
import (
"log"
"github.com/txix-open/isp-kit/http/endpoint"
"github.com/txix-open/isp-kit/http/endpoint/httplog"
log2 "github.com/txix-open/isp-kit/log"
)
func main() {
logger, err := log2.New()
if err != nil {
log.Fatal(err)
}
/* create wrapper with custom logging middleware */
wrapper := endpoint.DefaultWrapper(logger, httplog.LogWithOptions(
logger,
httplog.WithLogRequestBody(true), // enable logging request body
httplog.WithLogResponseBody(false), // disable logging response body
httplog.WithContentTypes([]string{"application/custom"}), // only for `application/custom` content-type
))
}
```
@@ -0,0 +1,215 @@
// Package httplog provides HTTP request/response logging middleware.
// It supports separate request and response body logging, combined logging,
// and content-type filtering.
package httplog
import (
"context"
"encoding/base64"
"net/http"
"strconv"
"strings"
"time"
"github.com/txix-open/isp-kit/errors"
http2 "github.com/txix-open/isp-kit/http"
"github.com/txix-open/isp-kit/http/endpoint"
"github.com/txix-open/isp-kit/http/endpoint/buffer"
"github.com/txix-open/isp-kit/log"
)
const (
// applicationNameHeader is the HTTP header for base64-encoded application name.
applicationNameHeader = "X-Application-Name"
// applicationIdHeader is the HTTP header for application identity (numeric ID).
applicationIdHeader = "X-Application-Identity"
)
var (
// defaultLogBodyContentTypes specifies the content types for which body logging is enabled.
defaultLogBodyContentTypes = []string{
"application/json",
"text/xml",
}
)
// logConfig holds the configuration for the logging middleware.
type logConfig struct {
logBodyContentTypes []string
logRequestBody bool
logResponseBody bool
combinedLog bool
}
// Log creates a logging middleware that logs requests and responses separately.
// If logBody is true, it logs request and response bodies for supported content types.
func Log(logger log.Logger, logBody bool) endpoint.LogMiddleware {
cfg := &logConfig{
logBodyContentTypes: defaultLogBodyContentTypes,
logRequestBody: logBody,
logResponseBody: logBody,
}
return middleware(logger, cfg)
}
// CombinedLog creates a logging middleware that logs requests and responses in a single entry.
// If logBody is true, it logs request and response bodies for supported content types.
func CombinedLog(logger log.Logger, logBody bool) endpoint.LogMiddleware {
cfg := &logConfig{
logBodyContentTypes: defaultLogBodyContentTypes,
logRequestBody: logBody,
logResponseBody: logBody,
}
return combinedLogMiddleware(logger, cfg)
}
// LogWithOptions creates a logging middleware with custom configuration options.
// By default, body logging is disabled. Use options like WithLogBody, WithCombinedLog
// to customize the behavior.
func LogWithOptions(logger log.Logger, opts ...Option) endpoint.LogMiddleware {
cfg := &logConfig{
logBodyContentTypes: defaultLogBodyContentTypes,
logRequestBody: false,
logResponseBody: false,
combinedLog: false,
}
for _, opt := range opts {
opt(cfg)
}
if cfg.combinedLog {
return combinedLogMiddleware(logger, cfg)
}
return middleware(logger, cfg)
}
// middleware creates a logging middleware that logs requests and responses separately.
func middleware(logger log.Logger, cfg *logConfig) endpoint.LogMiddleware {
return func(next http2.HandlerFunc) http2.HandlerFunc {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
buf := buffer.Acquire(w)
defer buffer.Release(buf)
now := time.Now()
requestLogFields := []log.Field{
log.String("method", r.Method),
log.String("url", r.URL.String()),
}
requestContentType := r.Header.Get("Content-Type")
if cfg.logRequestBody && matchContentType(requestContentType, cfg.logBodyContentTypes) {
err := buf.ReadRequestBody(r.Body)
if err != nil {
return errors.WithMessage(err, "read request body for logging")
}
err = r.Body.Close()
if err != nil {
return errors.WithMessage(err, "close request reader")
}
r.Body = buffer.NewRequestBody(buf.RequestBody())
requestLogFields = append(requestLogFields, log.ByteString("requestBody", buf.RequestBody()))
}
logger.Debug(ctx, "http handler: request", requestLogFields...)
err := next(ctx, buf, r)
responseLogFields := []log.Field{
log.Int("statusCode", buf.StatusCode()),
log.Int64("elapsedTimeMs", time.Since(now).Milliseconds()),
}
responseContentType := buf.Header().Get("Content-Type")
if cfg.logResponseBody && matchContentType(responseContentType, cfg.logBodyContentTypes) {
responseLogFields = append(responseLogFields, log.ByteString("responseBody", buf.ResponseBody()))
}
logger.Debug(ctx, "http handler: response", responseLogFields...)
return err
}
}
}
// combinedLogMiddleware creates a logging middleware that logs requests and responses in a single entry.
func combinedLogMiddleware(logger log.Logger, cfg *logConfig) endpoint.LogMiddleware {
return func(next http2.HandlerFunc) http2.HandlerFunc {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
buf := buffer.Acquire(w)
defer buffer.Release(buf)
now := time.Now()
logFields := []log.Field{
log.String("method", r.Method),
log.String("url", r.URL.String()),
}
logFields = append(logFields, applicationLogFields(r)...)
requestContentType := r.Header.Get("Content-Type")
if cfg.logRequestBody && matchContentType(requestContentType, cfg.logBodyContentTypes) {
err := buf.ReadRequestBody(r.Body)
if err != nil {
return errors.WithMessage(err, "read request body for logging")
}
err = r.Body.Close()
if err != nil {
return errors.WithMessage(err, "close request reader")
}
r.Body = buffer.NewRequestBody(buf.RequestBody())
logFields = append(logFields, log.ByteString("requestBody", buf.RequestBody()))
}
err := next(ctx, buf, r)
logFields = append(logFields,
log.Int("statusCode", buf.StatusCode()),
log.Int64("elapsedTimeMs", time.Since(now).Milliseconds()),
)
responseContentType := buf.Header().Get("Content-Type")
if cfg.logResponseBody && matchContentType(responseContentType, cfg.logBodyContentTypes) {
logFields = append(logFields, log.ByteString("responseBody", buf.ResponseBody()))
}
logger.Debug(ctx, "http handler: log", logFields...)
return err
}
}
}
// matchContentType checks if the given content type matches any of the available content types.
// It uses prefix matching to handle content types with parameters (e.g., "application/json; charset=utf-8").
func matchContentType(contentType string, availableContentTypes []string) bool {
for _, content := range availableContentTypes {
if strings.HasPrefix(contentType, content) {
return true
}
}
return false
}
// applicationLogFields extracts application-related log fields from the request.
// It decodes the base64-encoded application name and parses the application ID.
func applicationLogFields(r *http.Request) []log.Field {
logFields := make([]log.Field, 0)
appName := r.Header.Get(applicationNameHeader)
if appName != "" {
decodedName, err := base64.StdEncoding.DecodeString(appName)
if err == nil {
logFields = append(logFields, log.String("applicationName", string(decodedName)))
}
}
appId := r.Header.Get(applicationIdHeader)
if appId == "" {
return logFields
}
intAppId, err := strconv.Atoi(appId)
if err == nil {
logFields = append(logFields, log.Int("applicationId", intAppId))
}
return logFields
}
+19
View File
@@ -0,0 +1,19 @@
package httplog
import (
"context"
"net/http"
http2 "github.com/txix-open/isp-kit/http"
"github.com/txix-open/isp-kit/http/endpoint"
)
// Noop returns a no-operation logging middleware that simply passes through requests.
// It is useful as a placeholder or for testing when logging is not needed.
func Noop() endpoint.LogMiddleware {
return func(next http2.HandlerFunc) http2.HandlerFunc {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
return next(ctx, w, r)
}
}
}
+42
View File
@@ -0,0 +1,42 @@
package httplog
// Option is a function that configures the logConfig.
type Option func(cfg *logConfig)
// WithContentTypes sets the content types for which request and response bodies will be logged.
// Content types are matched using prefix comparison (e.g., "application/json" matches "application/json; charset=utf-8").
func WithContentTypes(logBodyContentTypes []string) Option {
return func(cfg *logConfig) {
cfg.logBodyContentTypes = logBodyContentTypes
}
}
// WithLogBody is a shortcut to enable both request and response body logging.
func WithLogBody(logBody bool) Option {
return func(cfg *logConfig) {
cfg.logResponseBody = logBody
cfg.logRequestBody = logBody
}
}
// WithLogResponseBody enables or disables response body logging.
func WithLogResponseBody(logResponseBody bool) Option {
return func(cfg *logConfig) {
cfg.logResponseBody = logResponseBody
}
}
// WithLogRequestBody enables or disables request body logging.
func WithLogRequestBody(logRequestBody bool) Option {
return func(cfg *logConfig) {
cfg.logRequestBody = logRequestBody
}
}
// WithCombinedLog enables or disables single combined log entry for request and response.
// When enabled, the middleware logs request and response in a single log entry instead of two separate entries.
func WithCombinedLog(enable bool) Option {
return func(cfg *logConfig) {
cfg.combinedLog = enable
}
}
+90
View File
@@ -0,0 +1,90 @@
package endpoint
import (
"context"
"io"
"net/http"
"reflect"
"unicode"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/http/apierrors"
"github.com/txix-open/isp-kit/json"
)
// Validator validates a value and returns whether it's valid along with field-level error details.
type Validator interface {
// Validate returns true if valid and a map of field names to error messages.
Validate(value any) (bool, map[string]string)
}
// JsonRequestExtractor extracts and validates JSON request bodies.
// It decodes JSON, validates the result, and returns business errors for invalid input.
type JsonRequestExtractor struct {
Validator Validator
}
// Extract decodes the JSON request body into a reflect.Value of the specified type.
// It validates the decoded value and returns a business error if validation fails.
func (j JsonRequestExtractor) Extract(ctx context.Context, reader io.Reader, reqBodyType reflect.Type) (reflect.Value, error) {
instance := reflect.New(reqBodyType)
err := j.extract(reader, instance.Interface())
if err != nil {
return reflect.Value{}, err
}
elem := instance.Elem()
err = j.validate(elem.Interface())
if err != nil {
return reflect.Value{}, err
}
return elem, nil
}
// ExtractV2 decodes the JSON request body into the provided pointer.
// It validates the decoded value and returns a business error if validation fails.
func (j JsonRequestExtractor) ExtractV2(_ context.Context, reader io.Reader, ptr any) error {
err := j.extract(reader, ptr)
if err != nil {
return err
}
return j.validate(ptr)
}
// extract decodes JSON from the reader into the target pointer.
// It returns a business error with HTTP 400 status for invalid JSON.
func (j JsonRequestExtractor) extract(reader io.Reader, ptr any) error {
err := json.NewDecoder(reader).Decode(ptr)
if err != nil {
err = errors.WithMessage(err, "unmarshal json request body")
return apierrors.NewBusinessError(http.StatusBadRequest, err.Error(), err)
}
return nil
}
// validate validates the decoded value using the configured validator.
// It returns a business error with validation details if validation fails.
func (j JsonRequestExtractor) validate(v any) error {
ok, details := j.Validator.Validate(v)
if ok {
return nil
}
formattedDetails := formatDetails(details)
return apierrors.NewBusinessError(
http.StatusBadRequest,
"invalid request body",
errors.Errorf("validation errors: %v", formattedDetails),
).WithDetails(formattedDetails)
}
// formatDetails converts validation error details by lowercasing the first letter of each field name.
func formatDetails(details map[string]string) map[string]any {
result := make(map[string]any, len(details))
for k, v := range details {
arr := []rune(k)
arr[0] = unicode.ToLower(arr[0])
result[string(arr)] = v
}
return result
}
+37
View File
@@ -0,0 +1,37 @@
package endpoint
import (
"context"
"net/http"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/json"
"github.com/txix-open/isp-kit/requestid"
)
// JsonResponseMapper maps response objects to JSON format.
// It sets the Content-Type header to application/json and includes the request ID in response headers.
type JsonResponseMapper struct {
}
// Map marshals the result to JSON and writes it to the http.ResponseWriter.
// It skips nil results and includes the request ID in the response headers if available.
func (j JsonResponseMapper) Map(ctx context.Context, result any, w http.ResponseWriter) error {
reqId := requestid.FromContext(ctx)
if reqId != "" {
w.Header().Set(requestid.Header, reqId)
}
if result == nil {
return nil
}
w.Header().Set("Content-Type", "application/json")
err := json.EncodeInto(w, result)
if err != nil {
return errors.WithMessage(err, "marshal json")
}
return nil
}
@@ -0,0 +1,71 @@
package endpoint
import (
"context"
"net/http"
"time"
http2 "github.com/txix-open/isp-kit/http"
"github.com/txix-open/isp-kit/http/endpoint/buffer"
"github.com/txix-open/isp-kit/metrics/http_metrics"
)
// scSource is an interface for retrieving the HTTP status code from a response.
type scSource interface {
StatusCode() int
}
// writerWrapper wraps http.ResponseWriter to capture the status code.
// It defaults to http.StatusOK if WriteHeader is not called.
type writerWrapper struct {
http.ResponseWriter
statusCode int
}
// StatusCode returns the captured status code, or http.StatusOK if not set.
func (w *writerWrapper) StatusCode() int {
if w.statusCode == 0 {
return http.StatusOK
}
return w.statusCode
}
// WriteHeader captures the status code and delegates to the underlying ResponseWriter.
func (w *writerWrapper) WriteHeader(statusCode int) {
w.statusCode = statusCode
w.ResponseWriter.WriteHeader(statusCode)
}
// Metrics is a middleware that collects HTTP server metrics for each endpoint.
// It records request duration, status code counts, and request/response body sizes.
// If the endpoint is not available in the context, it skips metrics collection.
func Metrics(storage *http_metrics.ServerStorage) http2.Middleware {
return func(next http2.HandlerFunc) http2.HandlerFunc {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
endpoint := http_metrics.ServerEndpoint(r.Context())
if endpoint == "" {
return next(ctx, w, r)
}
var scSrc scSource
buf, isBuffer := w.(*buffer.Buffer)
if isBuffer {
scSrc = buf
} else {
scSrc = &writerWrapper{ResponseWriter: w}
}
start := time.Now()
err := next(ctx, w, r)
storage.ObserveDuration(r.Method, endpoint, time.Since(start))
storage.CountStatusCode(r.Method, endpoint, scSrc.StatusCode())
if isBuffer {
storage.ObserveRequestBodySize(r.Method, endpoint, len(buf.RequestBody()))
storage.ObserveResponseBodySize(r.Method, endpoint, len(buf.ResponseBody()))
}
return err
}
}
}
+124
View File
@@ -0,0 +1,124 @@
package endpoint
import (
"context"
"fmt"
"net/http"
"github.com/getsentry/sentry-go"
http2 "github.com/txix-open/isp-kit/http"
"github.com/txix-open/isp-kit/http/apierrors"
"github.com/txix-open/isp-kit/log/logutil"
sentry2 "github.com/txix-open/isp-kit/observability/sentry"
"github.com/txix-open/isp-kit/panic_recovery"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/log"
"github.com/txix-open/isp-kit/requestid"
)
const (
// defaultMaxRequestBodySize is the default maximum allowed request body size (64MB).
defaultMaxRequestBodySize = 64 * 1024 * 1024
)
// LogMiddleware is an alias for http.Middleware used for request/response logging.
type LogMiddleware http2.Middleware
// MaxRequestBodySize limits the size of the request body that can be read.
// It wraps the request body with http.MaxBytesReader to enforce the limit.
func MaxRequestBodySize(maxBytes int64) http2.Middleware {
return func(next http2.HandlerFunc) http2.HandlerFunc {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
r.Body = http.MaxBytesReader(w, r.Body, maxBytes)
return next(ctx, w, r)
}
}
}
// Recovery is a middleware that catches panics and converts them to errors.
// It ensures the server remains stable even when handler code panics.
// Safe for concurrent use.
func Recovery() http2.Middleware {
return func(next http2.HandlerFunc) http2.HandlerFunc {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) (err error) {
defer panic_recovery.Recover(func(panicErr error) {
err = panicErr
})
return next(ctx, w, r)
}
}
}
// ErrorHandler is a middleware that logs errors and writes appropriate HTTP responses.
// It uses the error's logging level and enriches Sentry events with request details.
// For HttpError implementations, it writes the error using WriteError; otherwise,
// it returns a generic internal service error to hide implementation details.
func ErrorHandler(logger log.Logger) http2.Middleware {
return func(next http2.HandlerFunc) http2.HandlerFunc {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
err := next(ctx, w, r)
if err == nil {
return nil
}
logFunc := logutil.LogLevelFuncForError(err, logger)
logContext := sentry2.EnrichEvent(ctx, func(event *sentry.Event) {
event.Request = sentryRequest(r)
})
logFunc(logContext, err)
reqId := requestid.FromContext(ctx)
if reqId != "" {
w.Header().Set(requestid.Header, reqId)
}
var httpErr HttpError
if errors.As(err, &httpErr) {
err = httpErr.WriteError(w)
return err
}
// hide error details to prevent potential security leaks
err = apierrors.NewInternalServiceError(err).WriteError(w)
return err
}
}
}
// RequestId is a middleware that manages request IDs for tracing and logging.
// It uses the existing request ID from headers if present, or generates a new one.
// The request ID is added to the context and response headers.
func RequestId() http2.Middleware {
return func(next http2.HandlerFunc) http2.HandlerFunc {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
requestId := r.Header.Get(requestid.Header)
if requestId == "" {
requestId = requestid.Next()
}
ctx = requestid.ToContext(ctx, requestId)
ctx = log.ToContext(ctx, log.String(requestid.LogKey, requestId))
return next(ctx, w, r)
}
}
}
// sentryRequest creates a Sentry request object from an http.Request.
// It determines the protocol based on TLS or X-Forwarded-Proto header.
func sentryRequest(r *http.Request) *sentry.Request {
protocol := "https"
if r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https" {
protocol = "http"
}
url := fmt.Sprintf("%s://%s%s", protocol, r.Host, r.URL.Path)
return &sentry.Request{
URL: url,
Method: r.Method,
QueryString: r.URL.RawQuery,
}
}
+39
View File
@@ -0,0 +1,39 @@
package endpoint
import (
"context"
"net/http"
)
// ContextParam creates a ParamMapper that provides context.Context to endpoint functions.
// This is automatically included in the default wrapper.
func ContextParam() ParamMapper {
return ParamMapper{
Type: "context.Context",
Builder: func(ctx context.Context, w http.ResponseWriter, r *http.Request) (any, error) {
return ctx, nil
},
}
}
// ResponseWriterParam creates a ParamMapper that provides http.ResponseWriter to endpoint functions.
// This is automatically included in the default wrapper.
func ResponseWriterParam() ParamMapper {
return ParamMapper{
Type: "http.ResponseWriter",
Builder: func(ctx context.Context, w http.ResponseWriter, r *http.Request) (any, error) {
return w, nil
},
}
}
// RequestParam creates a ParamMapper that provides *http.Request to endpoint functions.
// This is automatically included in the default wrapper.
func RequestParam() ParamMapper {
return ParamMapper{
Type: "*http.Request",
Builder: func(ctx context.Context, w http.ResponseWriter, r *http.Request) (any, error) {
return r, nil
},
}
}
+123
View File
@@ -0,0 +1,123 @@
package endpoint
import (
"context"
"net/http"
http2 "github.com/txix-open/isp-kit/http"
)
// Wrappable is an interface for types that can be wrapped into an http.HandlerFunc.
// Implementations should handle request extraction and response mapping.
type Wrappable interface {
Wrap(wrapper Wrapper) http2.HandlerFunc
}
// basic is a generic endpoint function type that accepts a request and returns a response.
type basic[Req any, Res any] func(ctx context.Context, req Req) (Res, error)
// New creates a new generic endpoint with request and response types.
// The returned endpoint automatically handles JSON body extraction and response mapping.
func New[Req any, Res any](fn func(ctx context.Context, req Req) (Res, error)) basic[Req, Res] {
return fn
}
// Wrap implements Wrappable for basic endpoints.
// It extracts the request body, calls the endpoint function, and maps the response.
func (fn basic[Req, Res]) Wrap(wrapper Wrapper) http2.HandlerFunc {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
req, err := extractBody[Req](ctx, wrapper, r)
if err != nil {
return err
}
resp, err := fn(ctx, req)
if err != nil {
return err
}
return wrapper.BodyMapper.Map(ctx, resp, w)
}
}
// withoutResponseBody is an endpoint type that processes a request but returns no response body.
type withoutResponseBody[Req any] func(ctx context.Context, req Req) error
// NewWithoutResponse creates an endpoint that handles a request without returning a response body.
// Useful for operations like deletions or fire-and-forget actions.
func NewWithoutResponse[Req any](fn func(ctx context.Context, req Req) error) withoutResponseBody[Req] {
return fn
}
// Wrap implements Wrappable for endpoints without response body.
func (fn withoutResponseBody[Req]) Wrap(wrapper Wrapper) http2.HandlerFunc {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
req, err := extractBody[Req](ctx, wrapper, r)
if err != nil {
return err
}
return fn(ctx, req)
}
}
// withRequest is an endpoint type that has direct access to the http.Request.
type withRequest func(ctx context.Context, r *http.Request) error
// NewWithRequest creates an endpoint that receives the raw http.Request.
// Use this when you need direct access to headers, query parameters, or other request details.
func NewWithRequest(fn func(ctx context.Context, r *http.Request) error) withRequest {
return fn
}
// Wrap implements Wrappable for withRequest endpoints.
func (fn withRequest) Wrap(wrapper Wrapper) http2.HandlerFunc {
return func(ctx context.Context, _ http.ResponseWriter, r *http.Request) error {
return fn(ctx, r)
}
}
// withRequestAndResponse is an endpoint type that has direct access to http.Request and returns a typed response.
type withRequestAndResponse[Res any] func(ctx context.Context, r *http.Request) (Res, error)
// NewWithRequestAndResponse creates an endpoint with direct access to http.Request and automatic response mapping.
// Useful when you need direct access to request details while still returning a typed response.
func NewWithRequestAndResponse[Res any](fn func(ctx context.Context, r *http.Request) (Res, error)) withRequestAndResponse[Res] {
return fn
}
// Wrap implements Wrappable for withRequestAndResponse endpoints.
func (fn withRequestAndResponse[Res]) Wrap(wrapper Wrapper) http2.HandlerFunc {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
resp, err := fn(ctx, r)
if err != nil {
return err
}
return wrapper.BodyMapper.Map(ctx, resp, w)
}
}
// defaultHttp is an endpoint type that uses the standard http.HandlerFunc signature.
type defaultHttp http2.HandlerFunc
// NewDefaultHttp creates an endpoint with direct access to ResponseWriter and Request.
// This is the most flexible option but bypasses automatic body extraction and mapping.
func NewDefaultHttp(fn func(ctx context.Context, w http.ResponseWriter, r *http.Request) error) defaultHttp {
return fn
}
// Wrap implements Wrappable for defaultHttp endpoints.
func (fn defaultHttp) Wrap(wrapper Wrapper) http2.HandlerFunc {
return http2.HandlerFunc(fn)
}
// extractBody extracts and unmarshals the request body into the target type.
// It uses the wrapper's BodyExtractor to handle the request body.
func extractBody[T any](ctx context.Context, w Wrapper, r *http.Request) (T, error) {
var req T
err := w.BodyExtractor.ExtractV2(ctx, r.Body, &req)
if err != nil {
return *new(T), err
}
return req, nil
}
+133
View File
@@ -0,0 +1,133 @@
// Package endpoint provides a high-level abstraction for building HTTP endpoints
// with automatic request/response handling, validation, and middleware support.
// It uses Go generics to create type-safe endpoint implementations.
package endpoint
import (
"context"
"io"
"net/http"
"reflect"
"slices"
http2 "github.com/txix-open/isp-kit/http"
"github.com/txix-open/isp-kit/log"
)
// HttpError is an interface for errors that can write themselves to an HTTP response.
// Implementations should handle their own HTTP status codes and response formatting.
type HttpError interface {
WriteError(w http.ResponseWriter) error
}
// RequestBodyExtractor is responsible for extracting and unmarshaling request bodies.
// It supports both reflection-based and direct pointer-based extraction.
type RequestBodyExtractor interface {
// Extract extracts the request body into a reflect.Value of the specified type.
Extract(ctx context.Context, reader io.Reader, reqBodyType reflect.Type) (reflect.Value, error)
// ExtractV2 extracts the request body into a pointer directly.
ExtractV2(ctx context.Context, reader io.Reader, ptr any) error
}
// ResponseBodyMapper is responsible for marshaling and writing response bodies.
type ResponseBodyMapper interface {
// Map marshals the result and writes it to the http.ResponseWriter.
Map(ctx context.Context, result any, w http.ResponseWriter) error
}
// ParamBuilder is a function that builds a parameter value from the request context.
type ParamBuilder func(ctx context.Context, w http.ResponseWriter, r *http.Request) (any, error)
// ParamMapper maps a parameter type to its builder function.
type ParamMapper struct {
// Type is the string representation of the parameter type.
Type string
// Builder creates the parameter value from the request context.
Builder ParamBuilder
}
// Wrapper is the core component for building HTTP endpoints.
// It combines parameter mapping, body extraction, response mapping, and middleware support.
type Wrapper struct {
ParamMappers map[string]ParamMapper
BodyExtractor RequestBodyExtractor
BodyMapper ResponseBodyMapper
Middlewares []http2.Middleware
Logger log.Logger
}
// NewWrapper creates a new Wrapper with the specified configuration.
// Parameter mappers are stored in a map for efficient type lookup.
func NewWrapper(
paramMappers []ParamMapper,
bodyExtractor RequestBodyExtractor,
bodyMapper ResponseBodyMapper,
logger log.Logger,
) Wrapper {
mappers := make(map[string]ParamMapper)
for _, mapper := range paramMappers {
mappers[mapper.Type] = mapper
}
return Wrapper{
ParamMappers: mappers,
BodyExtractor: bodyExtractor,
BodyMapper: bodyMapper,
Logger: logger,
}
}
// Endpoint wraps a function as an http.HandlerFunc.
//
// Use EndpointV2 with New, NewWithoutResponse, NewWithRequest, or NewDefaultHttp instead.
// EndpointV2 avoids reflection overhead by using the Wrappable interface.
func (m Wrapper) Endpoint(f any) http.HandlerFunc {
w, isWrappable := f.(Wrappable)
if isWrappable {
return m.EndpointV2(w)
}
caller, err := NewCaller(f, m.BodyExtractor, m.BodyMapper, m.ParamMappers)
if err != nil {
panic(err)
}
handler := caller.Handle
for i := range slices.Backward(m.Middlewares) {
handler = m.Middlewares[i](handler)
}
return func(w http.ResponseWriter, r *http.Request) {
err := handler(r.Context(), w, r)
if err != nil {
m.Logger.Error(r.Context(), err)
}
}
}
// EndpointV2 wraps a Wrappable implementation as an http.HandlerFunc.
// It applies middleware in reverse order (last middleware executes first).
// This version avoids reflection overhead and is preferred for production use.
func (m Wrapper) EndpointV2(w Wrappable) http.HandlerFunc {
handler := w.Wrap(m)
for i := range slices.Backward(m.Middlewares) {
handler = m.Middlewares[i](handler)
}
return func(w http.ResponseWriter, r *http.Request) {
err := handler(r.Context(), w, r)
if err != nil {
m.Logger.Error(r.Context(), err)
}
}
}
// WithMiddlewares returns a new Wrapper with additional middleware appended.
// The original Wrapper remains unchanged (immutable).
func (m Wrapper) WithMiddlewares(middlewares ...http2.Middleware) Wrapper {
return Wrapper{
ParamMappers: m.ParamMappers,
BodyExtractor: m.BodyExtractor,
BodyMapper: m.BodyMapper,
Middlewares: append(m.Middlewares, middlewares...),
Logger: m.Logger,
}
}
+70
View File
@@ -0,0 +1,70 @@
# Package `router`
Пакет `router` предоставляет обертку над [`httprouter`](https://github.com/julienschmidt/httprouter) с поддержкой метрик
и удобной регистрацией обработчиков.
Интегрируется с системой мониторинга для отслеживания эндпоинтов.
## Types
### Router
Структура для управления HTTP-маршрутами. Обеспечивает регистрацию обработчиков, сбор метрик и работу с параметрами URL.
**Methods:**
#### `New() *Router`
Конструктор роутера.
#### `(r *Router) GET(path string, handler http.Handler) *Router`
Зарегистрировать обработчик для GET-запросов. Аналогичные методы: `POST()`, `PUT()`, `DELETE()`.
#### `(r *Router) Handler(method string, path string, handler http.Handler) *Router`
Зарегистрировать обработчик для произвольного HTTP-метода.
#### `(r *Router) ServeHTTP(writer http.ResponseWriter, request *http.Request)`
Обработать HTTP-запрос.
#### `(r *Router) InternalRouter() *httprouter.Router`
Возвращает внутренний экземпляр `httprouter.Router` для кастомных настроек.
## Functions
#### `ParamsFromRequest(http *http.Request) Params`
Извлечь URL-параметры из запроса.
#### `ParamsFromContext(ctx context.Context) Params`
Извлечь URL-параметры из контекста.
## Usage
### Default usage flow
```go
package main
import (
"log"
"net/http"
"github.com/txix-open/isp-kit/http/router"
)
func main() {
r := router.New()
r.GET("/users/:id", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
params := router.ParamsFromRequest(r)
userId := params.ByName("id") /* get id param */
log.Println(userId)
w.WriteHeader(http.StatusOK)
}))
_ = http.ListenAndServe(":8080", r)
}
```
+93
View File
@@ -0,0 +1,93 @@
// Package router provides HTTP request routing with metrics integration.
// It wraps the julienschmidt/httprouter library and adds automatic endpoint metrics collection.
package router
import (
"context"
"fmt"
"net/http"
"github.com/julienschmidt/httprouter"
"github.com/txix-open/isp-kit/metrics/http_metrics"
)
// Params is an alias for httprouter.Params, representing URL path parameters.
type Params = httprouter.Params
// Router wraps httprouter.Router with automatic metrics collection for each endpoint.
// It supports method-based routing (GET, POST, PUT, DELETE) and fluent API for route configuration.
type Router struct {
router *httprouter.Router
}
// New creates a new Router instance with a fresh httprouter backend.
func New() *Router {
return &Router{
router: httprouter.New(),
}
}
// GET registers an HTTP GET handler for the specified path.
// Returns the Router for fluent chaining.
func (r *Router) GET(path string, handler http.Handler) *Router {
return r.Handler(http.MethodGet, path, handler)
}
// POST registers an HTTP POST handler for the specified path.
// Returns the Router for fluent chaining.
func (r *Router) POST(path string, handler http.Handler) *Router {
return r.Handler(http.MethodPost, path, handler)
}
// PUT registers an HTTP PUT handler for the specified path.
// Returns the Router for fluent chaining.
func (r *Router) PUT(path string, handler http.Handler) *Router {
return r.Handler(http.MethodPut, path, handler)
}
// DELETE registers an HTTP DELETE handler for the specified path.
// Returns the Router for fluent chaining.
func (r *Router) DELETE(path string, handler http.Handler) *Router {
return r.Handler(http.MethodDelete, path, handler)
}
// Handler registers a handler for the specified HTTP method and path.
// It automatically wraps the handler with metrics collection.
// Returns the Router for fluent chaining.
func (r *Router) Handler(method string, path string, handler http.Handler) *Router {
r.router.Handler(method, path, r.withMetricEndpoint(method, path, handler))
return r
}
// ServeHTTP implements the http.Handler interface and delegates to the underlying httprouter.
func (r *Router) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
r.router.ServeHTTP(writer, request)
}
// InternalRouter returns the underlying httprouter instance for advanced configuration.
func (r *Router) InternalRouter() *httprouter.Router {
return r.router
}
// withMetricEndpoint wraps a handler to add endpoint metrics to the request context.
// The endpoint is formatted as "METHOD /path" for metrics identification.
func (r *Router) withMetricEndpoint(method string, path string, handler http.Handler) http.Handler {
endpoint := fmt.Sprintf("%s %s", method, path)
return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
ctx := http_metrics.ServerEndpointToContext(request.Context(), endpoint)
request = request.WithContext(ctx)
handler.ServeHTTP(writer, request)
})
}
// ParamsFromRequest extracts URL path parameters from an http.Request.
// It retrieves the parameters from the request context.
func ParamsFromRequest(http *http.Request) Params {
return ParamsFromContext(http.Context())
}
// ParamsFromContext extracts URL path parameters from a context.
// It returns empty params if none are present in the context.
func ParamsFromContext(ctx context.Context) Params {
return httprouter.ParamsFromContext(ctx)
}
+115
View File
@@ -0,0 +1,115 @@
// nolint:mnd
package http
import (
"context"
"net"
"net/http"
"sync/atomic"
"time"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/http/apierrors"
"github.com/txix-open/isp-kit/log"
)
// service is an internal wrapper that delegates to the actual HTTP handler.
// It uses atomic.Value for thread-safe handler replacement.
type service struct {
delegate atomic.Value
}
// ServeHTTP implements the http.Handler interface and delegates to the stored handler.
// It returns an internal service error if the handler is not initialized.
func (s *service) ServeHTTP(w http.ResponseWriter, r *http.Request) {
value, ok := s.delegate.Load().(http.Handler)
if !ok {
_ = apierrors.NewInternalServiceError(errors.New("handler is not initialized")).
WriteError(w)
return
}
value.ServeHTTP(w, r)
}
// ServerOption is a function that configures a Server instance.
type ServerOption func(*Server)
// WithServer allows providing a custom *http.Server for advanced configuration.
func WithServer(server *http.Server) ServerOption {
return func(srv *Server) {
srv.server = server
}
}
// Server wraps an http.Server with additional functionality for handler management.
// It provides graceful shutdown and handler upgrade capabilities.
type Server struct {
server *http.Server
service *service
}
// NewServer creates a new HTTP server with the specified logger and options.
// Default timeouts are set: 3 seconds for ReadHeaderTimeout and 120 seconds for IdleTimeout.
// Server is safe for concurrent use.
func NewServer(logger log.Logger, opts ...ServerOption) *Server {
s := &Server{
server: &http.Server{
ReadHeaderTimeout: 3 * time.Second,
IdleTimeout: 120 * time.Second,
ErrorLog: log.StdLoggerWithLevel(
logger,
log.WarnLevel,
log.String("worker", "http server"),
),
},
service: &service{
delegate: atomic.Value{},
},
}
for _, opts := range opts {
opts(s)
}
s.server.Handler = s.service
return s
}
// Shutdown gracefully shuts down the server without interrupting any active connections.
// It delegates to the underlying http.Server.Shutdown method.
func (s *Server) Shutdown(ctx context.Context) error {
return s.server.Shutdown(ctx)
}
// Upgrade replaces the current HTTP handler with a new one.
// This method is safe for concurrent use.
func (s *Server) Upgrade(handler http.Handler) {
s.service.delegate.Store(handler)
}
// ListenAndServe starts the server on the specified address.
// It creates a TCP listener and delegates to Serve.
func (s *Server) ListenAndServe(address string) error {
var lc net.ListenConfig
listener, err := lc.Listen(context.Background(), "tcp", address)
if err != nil {
return errors.WithMessagef(err, "listen: %s", address)
}
return s.Serve(listener)
}
// Serve accepts incoming connections on the specified listener and handles requests.
// It returns nil when the server is gracefully shut down.
func (s *Server) Serve(listener net.Listener) error {
err := s.server.Serve(listener)
if errors.Is(err, http.ErrServerClosed) {
return nil
}
if err != nil {
return errors.WithMessage(err, "serve http")
}
return nil
}
@@ -0,0 +1,61 @@
# Package `server_tracing`
Пакет `server_tracing` предоставляет middleware для серверной части HTTP-приложения, обеспечивая автоматическое создание span'ов OpenTelemetry для обработки входящих HTTP-запросов.
## Types
### Config
Структура `Config` определяет настройки трассировки для входящих HTTP-запросов.
**Fields:**
#### `Provider tracing.TracerProvider`
Провайдер трассировки (по умолчанию `tracing.DefaultProvider`).
#### `Propagator tracing.Propagator`
Пропагатор контекста (по умолчанию `tracing.DefaultPropagator`).
**Methods:**
#### `NewConfig() Config`
Создаёт конфигурацию с провайдером и пропагатором по умолчанию:
#### `func (c Config) Middleware() http2.Middleware`
Возвращает middleware, который добавляет в контекст обработки запроса OpenTelemetry span с необходимыми атрибутами. При этом:
- Используется `Propagator` для извлечения контекста трассировки из входящего запроса.
- Определяется имя span'а на основе маршрута или метода + пути.
- В span записываются стандартные HTTP-атрибуты, request ID, а также (если используется `buffer.Buffer`) количество прочитанных и записанных байт.
- Ошибки логируются и, если уровень логирования `Error`, также записываются в span через `RecordError`.
## Usage
### Default usage flow
```go
package main
import (
"github.com/txix-open/isp-kit/observability/tracing/http/server_tracing"
"github.com/txix-open/isp-kit/http"
)
func main(){
...
tracingCfg := server_tracing.NewConfig()
mux := http.NewServeMux()
handler := http.WrapHandler(tracingCfg.Middleware())(func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
// обработка запроса
return nil
})
mux.Handle("/example", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_ = handler(r.Context(), w, r)
}))
...
}
```
@@ -0,0 +1,117 @@
// Package server_tracing provides HTTP server middleware for distributed tracing.
package server_tracing
import (
"context"
"fmt"
"net/http"
http2 "github.com/txix-open/isp-kit/http"
"github.com/txix-open/isp-kit/http/endpoint/buffer"
"github.com/txix-open/isp-kit/log"
"github.com/txix-open/isp-kit/log/logutil"
"github.com/txix-open/isp-kit/metrics/http_metrics"
"github.com/txix-open/isp-kit/observability/tracing"
"github.com/txix-open/isp-kit/observability/tracing/http/semconvutil"
"github.com/txix-open/isp-kit/requestid"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/propagation"
semconv "go.opentelemetry.io/otel/semconv/v1.21.0"
"go.opentelemetry.io/otel/trace"
)
// ReadBytesKey is the attribute key for the total number of bytes read from the request body.
var ReadBytesKey = attribute.Key("http.read_bytes")
// WroteBytesKey is the attribute key for the total number of bytes written to the response.
var WroteBytesKey = attribute.Key("http.wrote_bytes")
// tracerName identifies the tracer for HTTP server tracing.
const tracerName = "isp-kit/observability/tracing/http"
// Config holds the configuration for the HTTP server tracing middleware.
type Config struct {
// Provider is the tracer provider used to create tracers.
Provider tracing.TracerProvider
// Propagator is the text map propagator for context propagation.
Propagator tracing.Propagator
}
// NewConfig creates a new Config with default values.
func NewConfig() Config {
return Config{
Provider: tracing.DefaultProvider,
Propagator: tracing.DefaultPropagator,
}
}
// Middleware returns an HTTP server middleware that creates spans for incoming requests.
// It extracts trace context from request headers, creates a server span, and sets
// appropriate attributes including status code and request details. If the provider
// is a no-op, it returns a pass-through middleware.
func (c Config) Middleware() http2.Middleware {
if tracing.IsNoop(c.Provider) {
return func(next http2.HandlerFunc) http2.HandlerFunc {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
return next(ctx, w, r)
}
}
}
tracer := c.Provider.Tracer(tracerName)
return func(next http2.HandlerFunc) http2.HandlerFunc {
return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
ctx = c.Propagator.Extract(ctx, propagation.HeaderCarrier(r.Header))
attributes := semconvutil.HTTPServerRequest("", r)
attributes = append(attributes, tracing.RequestId.String(requestid.FromContext(ctx)))
opts := []trace.SpanStartOption{
trace.WithSpanKind(trace.SpanKindServer),
}
var spanName string
serverEndpoint := http_metrics.ServerEndpoint(ctx)
if serverEndpoint != "" {
attributes = append(attributes, semconv.HTTPRouteKey.String(serverEndpoint))
spanName = serverEndpoint
} else {
spanName = fmt.Sprintf("%s %s", r.Method, r.URL.Path)
}
ctx, span := tracer.Start(ctx, spanName, opts...)
defer span.End()
var scSource scSource
buff, isBuffer := w.(*buffer.Buffer)
if isBuffer {
scSource = buff
} else {
scSource = &writerWrapper{ResponseWriter: w}
}
err := next(ctx, scSource, r)
if isBuffer {
attributes = append(
attributes,
ReadBytesKey.Int(len(buff.RequestBody())),
WroteBytesKey.Int(len(buff.ResponseBody())),
)
}
attributes = append(
attributes,
semconv.HTTPStatusCode(scSource.StatusCode()),
)
if err != nil {
logLevel := logutil.LogLevelForError(err)
if logLevel == log.ErrorLevel {
span.RecordError(err)
}
}
span.SetStatus(semconvutil.HTTPServerStatus(scSource.StatusCode()))
span.SetAttributes(attributes...)
return err
}
}
}
@@ -0,0 +1,48 @@
package server_tracing
import (
"bufio"
"net"
"net/http"
"github.com/txix-open/isp-kit/errors"
)
// scSource is an interface for HTTP response writers that provide status code access.
type scSource interface {
http.ResponseWriter
// StatusCode returns the HTTP status code.
StatusCode() int
}
// writerWrapper wraps an http.ResponseWriter to capture the status code.
type writerWrapper struct {
http.ResponseWriter
// statusCode holds the captured HTTP status code.
statusCode int
}
// Hijack implements the http.Hijacker interface by delegating to the upstream response writer.
// It returns an error if the upstream does not support hijacking.
func (w *writerWrapper) Hijack() (net.Conn, *bufio.ReadWriter, error) {
upstream, ok := w.ResponseWriter.(http.Hijacker)
if !ok {
return nil, nil, errors.New("writerWrapper: upstream writer doesn't implement Hijack")
}
return upstream.Hijack()
}
// StatusCode returns the captured HTTP status code, or http.StatusOK if not yet set.
func (w *writerWrapper) StatusCode() int {
if w.statusCode == 0 {
return http.StatusOK
}
return w.statusCode
}
// WriteHeader captures the status code and delegates to the upstream response writer.
func (w *writerWrapper) WriteHeader(statusCode int) {
w.statusCode = statusCode
w.ResponseWriter.WriteHeader(statusCode)
}