Compare commits

..

No commits in common. "main" and "backup" have entirely different histories.
main ... backup

21 changed files with 830 additions and 800 deletions

View File

@ -2,12 +2,19 @@ package web
import (
"errors"
"io"
"net/http"
"git.akyoto.dev/go/router"
)
// Context is the interface for a request and its response.
// Context represents the interface for a request & response context.
type Context interface {
Copy(io.Reader) error
Bytes([]byte) error
Error(...any) error
File(string) error
Get(string) string
Next() error
Redirect(int, string) error
Request() Request
@ -16,22 +23,29 @@ type Context interface {
String(string) error
}
// context contains the request and response data.
type context struct {
request
response
// ctx represents a request & response context.
type ctx struct {
request request
response response
server *server
params []router.Parameter
handlerCount uint8
}
// Bytes adds the raw byte slice to the response body.
func (ctx *context) Bytes(body []byte) error {
ctx.response.body = append(ctx.response.body, body...)
return nil
// Bytes responds with a raw byte slice.
func (ctx *ctx) Bytes(body []byte) error {
_, err := ctx.response.Write(body)
return err
}
// Error provides a convenient way to wrap multiple errors.
func (ctx *context) Error(messages ...any) error {
// Copy sends the contents of the io.Reader without creating an in-memory copy.
func (ctx *ctx) Copy(reader io.Reader) error {
_, err := io.Copy(ctx.response.ResponseWriter, reader)
return err
}
// Error is used for sending error messages to the client.
func (ctx *ctx) Error(messages ...any) error {
var combined []error
for _, msg := range messages {
@ -46,39 +60,64 @@ func (ctx *context) Error(messages ...any) error {
return errors.Join(combined...)
}
// Get retrieves a parameter.
func (ctx *ctx) Get(param string) string {
for i := range len(ctx.params) {
p := ctx.params[i]
if p.Key == param {
return p.Value
}
}
return ""
}
// File serves the file at the given path.
func (ctx *ctx) File(path string) error {
http.ServeFile(ctx.response.ResponseWriter, ctx.request.Request, path)
return nil
}
// Next executes the next handler in the middleware chain.
func (ctx *context) Next() error {
func (ctx *ctx) Next() error {
ctx.handlerCount++
return ctx.server.handlers[ctx.handlerCount](ctx)
}
// Redirect redirects the client to a different location
// with the specified status code.
func (ctx *context) Redirect(status int, location string) error {
ctx.response.SetStatus(status)
ctx.response.SetHeader("Location", location)
return nil
}
// Request returns the HTTP request.
func (ctx *context) Request() Request {
func (ctx *ctx) Request() Request {
return &ctx.request
}
// Response returns the HTTP response.
func (ctx *context) Response() Response {
func (ctx *ctx) Response() Response {
return &ctx.response
}
// Status sets the HTTP status of the response
// and returns the context for method chaining.
func (ctx *context) Status(status int) Context {
ctx.response.SetStatus(status)
// Redirect sets the Location header and writes the headers with the given status code.
func (ctx *ctx) Redirect(code int, url string) error {
ctx.Response().SetHeader("Location", url)
ctx.Status(code)
return nil
}
// Status sets the HTTP status of the response.
func (ctx *ctx) Status(status int) Context {
ctx.response.WriteHeader(status)
return ctx
}
// String adds the given string to the response body.
func (ctx *context) String(body string) error {
ctx.response.body = append(ctx.response.body, body...)
return nil
// String responds with the given string.
func (ctx *ctx) String(body string) error {
_, err := ctx.response.WriteString(body)
return err
}
// addParameter adds a new parameter to the context.
func (ctx *ctx) addParameter(key string, value string) {
ctx.params = append(ctx.params, router.Parameter{
Key: key,
Value: value,
})
}

View File

@ -1,69 +0,0 @@
package web_test
import (
"errors"
"testing"
"git.akyoto.dev/go/assert"
"git.akyoto.dev/go/web"
)
func TestBytes(t *testing.T) {
s := web.NewServer()
s.Get("/", func(ctx web.Context) error {
return ctx.Bytes([]byte("Hello"))
})
response := s.Request("GET", "/", nil, nil)
assert.Equal(t, response.Status(), 200)
assert.Equal(t, string(response.Body()), "Hello")
}
func TestString(t *testing.T) {
s := web.NewServer()
s.Get("/", func(ctx web.Context) error {
return ctx.String("Hello")
})
response := s.Request("GET", "/", nil, nil)
assert.Equal(t, response.Status(), 200)
assert.Equal(t, string(response.Body()), "Hello")
}
func TestError(t *testing.T) {
s := web.NewServer()
s.Get("/", func(ctx web.Context) error {
return ctx.Status(401).Error("Not logged in")
})
response := s.Request("GET", "/", nil, nil)
assert.Equal(t, response.Status(), 401)
assert.Equal(t, string(response.Body()), "")
}
func TestErrorMultiple(t *testing.T) {
s := web.NewServer()
s.Get("/", func(ctx web.Context) error {
return ctx.Status(401).Error("Not logged in", errors.New("Missing auth token"))
})
response := s.Request("GET", "/", nil, nil)
assert.Equal(t, response.Status(), 401)
assert.Equal(t, string(response.Body()), "")
}
func TestRedirect(t *testing.T) {
s := web.NewServer()
s.Get("/", func(ctx web.Context) error {
return ctx.Redirect(301, "/target")
})
response := s.Request("GET", "/", nil, nil)
assert.Equal(t, response.Status(), 301)
assert.Equal(t, response.Header("Location"), "/target")
}

View File

@ -1,7 +0,0 @@
package web
// Header is used to store HTTP headers.
type Header struct {
Key string
Value string
}

View File

@ -1,12 +1,12 @@
# web
A fast HTTP/1.1 web server that can sit behind a reverse proxy like `caddy` or `nginx` for HTTP 1/2/3 support.
Web server.
## Features
- High performance
- Low latency
- Scales incredibly well with the number of routes
- Radix tree routing
## Installation
@ -26,23 +26,12 @@ s.Get("/", func(ctx web.Context) error {
// Parameter route
s.Get("/blog/:post", func(ctx web.Context) error {
return ctx.String(ctx.Request().Param("post"))
return ctx.String(ctx.Get("post"))
})
// Wildcard route
s.Get("/images/*file", func(ctx web.Context) error {
return ctx.String(ctx.Request().Param("file"))
})
// Middleware
s.Use(func(ctx web.Context) error {
start := time.Now()
defer func() {
fmt.Println(ctx.Request().Path(), time.Since(start))
}()
return ctx.Next()
return ctx.String(ctx.Get("file"))
})
s.Run(":8080")
@ -51,33 +40,23 @@ s.Run(":8080")
## Tests
```
PASS: TestBytes
PASS: TestString
PASS: TestError
PASS: TestErrorMultiple
PASS: TestRedirect
PASS: TestRequest
PASS: TestRequestHeader
PASS: TestRequestParam
PASS: TestWrite
PASS: TestWriteString
PASS: TestResponseCompression
PASS: TestResponseHeader
PASS: TestResponseHeaderOverwrite
PASS: TestRouter
PASS: TestMiddleware
PASS: TestPanic
PASS: TestRun
PASS: TestBadRequest
PASS: TestBadRequestHeader
PASS: TestBadRequestMethod
PASS: TestBadRequestProtocol
PASS: TestEarlyClose
PASS: TestUnavailablePort
coverage: 100.0% of statements
```
## Benchmarks
![wrk Benchmark](https://i.imgur.com/6cDeZVA.png)
```
BenchmarkStatic/#00-12 32963155 30.88 ns/op 0 B/op 0 allocs/op
BenchmarkStatic/hello-12 31640433 37.92 ns/op 0 B/op 0 allocs/op
BenchmarkStatic/hello/world-12 22497412 52.57 ns/op 0 B/op 0 allocs/op
BenchmarkGitHub/gists/:id-12 24162244 49.70 ns/op 0 B/op 0 allocs/op
BenchmarkGitHub/repos/:a/:b-12 18865028 59.22 ns/op 0 B/op 0 allocs/op
```
## License
@ -85,4 +64,4 @@ Please see the [license documentation](https://akyoto.dev/license).
## Copyright
© 2024 Eduard Urbach
© 2023 Eduard Urbach

View File

@ -1,82 +1,63 @@
package web
import (
"bufio"
"git.akyoto.dev/go/router"
"context"
"net/http"
)
// Request is an interface for HTTP requests.
type Request interface {
Header(string) string
Context() context.Context
Header(key string) string
Host() string
Method() string
Path() string
Protocol() string
Read([]byte) (int, error)
Scheme() string
Param(string) string
}
// request represents the HTTP request used in the given context.
type request struct {
reader *bufio.Reader
scheme string
host string
method string
path string
query string
headers []Header
body []byte
params []router.Parameter
*http.Request
}
// Context returns the request context.
func (req request) Context() context.Context {
return req.Request.Context()
}
// Header returns the header value for the given key.
func (req *request) Header(key string) string {
for _, header := range req.headers {
if header.Key == key {
return header.Value
}
}
return ""
}
// Host returns the requested host.
func (req *request) Host() string {
return req.host
func (req request) Header(key string) string {
return req.Request.Header.Get(key)
}
// Method returns the request method.
func (req *request) Method() string {
return req.method
func (req request) Method() string {
return req.Request.Method
}
// Param retrieves a parameter.
func (req *request) Param(name string) string {
for i := range len(req.params) {
p := req.params[i]
// Protocol returns the request protocol.
func (req request) Protocol() string {
return req.Request.Proto
}
if p.Key == name {
return p.Value
}
}
return ""
// Host returns the requested host.
func (req request) Host() string {
return req.Request.Host
}
// Path returns the requested path.
func (req *request) Path() string {
return req.path
func (req request) Path() string {
return req.Request.URL.Path
}
// Scheme returns either `http`, `https` or an empty string.
// // Read implements the io.Reader interface and reads the request body.
func (req request) Read(buffer []byte) (int, error) {
return req.Request.Body.Read(buffer)
}
// Scheme returns either `http` or `https`.
func (req request) Scheme() string {
return req.scheme
}
// addParameter adds a new parameter to the request.
func (req *request) addParameter(key string, value string) {
req.params = append(req.params, router.Parameter{
Key: key,
Value: value,
})
return req.Request.URL.Scheme
}

View File

@ -1,54 +0,0 @@
package web_test
import (
"fmt"
"testing"
"git.akyoto.dev/go/assert"
"git.akyoto.dev/go/web"
)
func TestRequest(t *testing.T) {
s := web.NewServer()
s.Get("/request", func(ctx web.Context) error {
req := ctx.Request()
method := req.Method()
scheme := req.Scheme()
host := req.Host()
path := req.Path()
return ctx.String(fmt.Sprintf("%s %s %s %s", method, scheme, host, path))
})
response := s.Request("GET", "http://example.com/request?x=1", []web.Header{{"Accept", "*/*"}}, nil)
assert.Equal(t, response.Status(), 200)
assert.Equal(t, string(response.Body()), "GET http example.com /request")
}
func TestRequestHeader(t *testing.T) {
s := web.NewServer()
s.Get("/", func(ctx web.Context) error {
accept := ctx.Request().Header("Accept")
empty := ctx.Request().Header("")
return ctx.String(accept + empty)
})
response := s.Request("GET", "/", []web.Header{{"Accept", "*/*"}}, nil)
assert.Equal(t, response.Status(), 200)
assert.Equal(t, string(response.Body()), "*/*")
}
func TestRequestParam(t *testing.T) {
s := web.NewServer()
s.Get("/blog/:article", func(ctx web.Context) error {
article := ctx.Request().Param("article")
empty := ctx.Request().Param("")
return ctx.String(article + empty)
})
response := s.Request("GET", "/blog/my-article", nil, nil)
assert.Equal(t, response.Status(), 200)
assert.Equal(t, string(response.Body()), "my-article")
}

View File

@ -2,78 +2,48 @@ package web
import (
"io"
"net/http"
)
// Response is the interface for an HTTP response.
type Response interface {
io.Writer
io.StringWriter
Body() []byte
Header(string) string
Flush()
Header(key string) string
SetHeader(key string, value string)
SetBody([]byte)
SetStatus(int)
Status() int
Write([]byte) (int, error)
WriteString(string) (int, error)
}
// response represents the HTTP response used in the given context.
type response struct {
body []byte
headers []Header
status uint16
http.ResponseWriter
}
// Body returns the response body.
func (res *response) Body() []byte {
return res.body
// Flush flushes the response buffers to the client.
func (res response) Flush() {
flusher, ok := res.ResponseWriter.(http.Flusher)
if ok {
flusher.Flush()
}
}
// Header returns the header value for the given key.
func (res *response) Header(key string) string {
for _, header := range res.headers {
if header.Key == key {
return header.Value
}
}
return ""
func (res response) Header(key string) string {
return res.ResponseWriter.Header().Get(key)
}
// SetHeader sets the header value for the given key.
func (res *response) SetHeader(key string, value string) {
for i, header := range res.headers {
if header.Key == key {
res.headers[i].Value = value
return
}
}
res.headers = append(res.headers, Header{Key: key, Value: value})
}
// SetBody replaces the response body with the new contents.
func (res *response) SetBody(body []byte) {
res.body = body
}
// SetStatus sets the HTTP status code.
func (res *response) SetStatus(status int) {
res.status = uint16(status)
}
// Status returns the HTTP status code.
func (res *response) Status() int {
return int(res.status)
func (res response) SetHeader(key string, value string) {
res.ResponseWriter.Header().Set(key, value)
}
// Write implements the io.Writer interface.
func (res *response) Write(body []byte) (int, error) {
res.body = append(res.body, body...)
return len(body), nil
func (res response) Write(body []byte) (int, error) {
return res.ResponseWriter.Write(body)
}
// WriteString implements the io.StringWriter interface.
func (res *response) WriteString(body string) (int, error) {
res.body = append(res.body, body...)
return len(body), nil
func (res response) WriteString(body string) (int, error) {
return res.ResponseWriter.(io.StringWriter).WriteString(body)
}

View File

@ -1,100 +0,0 @@
package web_test
import (
"bytes"
"compress/gzip"
"io"
"testing"
"git.akyoto.dev/go/assert"
"git.akyoto.dev/go/web"
)
func TestWrite(t *testing.T) {
s := web.NewServer()
s.Get("/", func(ctx web.Context) error {
_, err := ctx.Response().Write([]byte("Hello"))
return err
})
response := s.Request("GET", "/", nil, nil)
assert.Equal(t, response.Status(), 200)
assert.Equal(t, string(response.Body()), "Hello")
}
func TestWriteString(t *testing.T) {
s := web.NewServer()
s.Get("/", func(ctx web.Context) error {
_, err := io.WriteString(ctx.Response(), "Hello")
return err
})
response := s.Request("GET", "/", nil, nil)
assert.Equal(t, response.Status(), 200)
assert.Equal(t, string(response.Body()), "Hello")
}
func TestResponseCompression(t *testing.T) {
s := web.NewServer()
uncompressed := bytes.Repeat([]byte("This text should be compressed to a size smaller than the original."), 5)
s.Use(func(ctx web.Context) error {
defer func() {
body := ctx.Response().Body()
ctx.Response().SetBody(nil)
zip := gzip.NewWriter(ctx.Response())
zip.Write(body)
zip.Close()
}()
return ctx.Next()
})
s.Get("/", func(ctx web.Context) error {
return ctx.Bytes(uncompressed)
})
response := s.Request("GET", "/", nil, nil)
assert.Equal(t, response.Status(), 200)
assert.True(t, len(response.Body()) < len(uncompressed))
reader, err := gzip.NewReader(bytes.NewReader(response.Body()))
assert.Nil(t, err)
decompressed, err := io.ReadAll(reader)
assert.Nil(t, err)
assert.DeepEqual(t, decompressed, uncompressed)
}
func TestResponseHeader(t *testing.T) {
s := web.NewServer()
s.Get("/", func(ctx web.Context) error {
ctx.Response().SetHeader("Content-Type", "text/plain")
contentType := ctx.Response().Header("Content-Type")
return ctx.String(contentType)
})
response := s.Request("GET", "/", nil, nil)
assert.Equal(t, response.Status(), 200)
assert.Equal(t, response.Header("Content-Type"), "text/plain")
assert.Equal(t, response.Header("Non existent header"), "")
assert.Equal(t, string(response.Body()), "text/plain")
}
func TestResponseHeaderOverwrite(t *testing.T) {
s := web.NewServer()
s.Get("/", func(ctx web.Context) error {
ctx.Response().SetHeader("Content-Type", "text/plain")
ctx.Response().SetHeader("Content-Type", "text/html")
return nil
})
response := s.Request("GET", "/", nil, nil)
assert.Equal(t, response.Status(), 200)
assert.Equal(t, response.Header("Content-Type"), "text/html")
assert.Equal(t, string(response.Body()), "")
}

243
Server.go
View File

@ -1,15 +1,12 @@
package web
import (
"bufio"
"bytes"
"io"
"context"
"log"
"net"
"net/http"
"os"
"os/signal"
"strconv"
"strings"
"sync"
"syscall"
@ -18,8 +15,11 @@ import (
// Server is the interface for an HTTP server.
type Server interface {
http.Handler
Delete(path string, handler Handler)
Get(path string, handler Handler)
Request(method string, path string, headers []Header, body io.Reader) Response
Post(path string, handler Handler)
Put(path string, handler Handler)
Router() *router.Router[Handler]
Run(address string) error
Use(handlers ...Handler)
@ -27,85 +27,116 @@ type Server interface {
// server is an HTTP server.
type server struct {
pool sync.Pool
handlers []Handler
contextPool sync.Pool
router *router.Router[Handler]
router router.Router[Handler]
errorHandler func(Context, error)
config config
}
// NewServer creates a new HTTP server.
func NewServer() Server {
r := &router.Router[Handler]{}
s := &server{
router: r,
router: router.Router[Handler]{},
config: defaultConfig(),
handlers: []Handler{
func(c Context) error {
ctx := c.(*context)
handler := r.LookupNoAlloc(ctx.request.method, ctx.request.path, ctx.request.addParameter)
ctx := c.(*ctx)
method := ctx.request.Method()
path := ctx.request.Path()
handler := ctx.server.router.LookupNoAlloc(method, path, ctx.addParameter)
if handler == nil {
ctx.SetStatus(404)
return nil
return ctx.Status(http.StatusNotFound).String(http.StatusText(http.StatusNotFound))
}
return handler(c)
},
},
errorHandler: func(ctx Context, err error) {
ctx.Response().WriteString(err.Error())
log.Println(ctx.Request().Path(), err)
},
}
s.contextPool.New = func() any { return s.newContext() }
s.pool.New = func() any {
return &ctx{
server: s,
params: make([]router.Parameter, 0, 8),
}
}
return s
}
// Get registers your function to be called when the given GET path has been requested.
func (s *server) Get(path string, handler Handler) {
s.Router().Add("GET", path, handler)
s.Router().Add(http.MethodGet, path, handler)
}
// Request performs a synthetic request and returns the response.
// This function keeps the response in memory so it's slightly slower than a real request.
// However it is very useful inside tests where you don't want to spin up a real web server.
func (s *server) Request(method string, url string, headers []Header, body io.Reader) Response {
ctx := s.newContext()
ctx.request.headers = headers
s.handleRequest(ctx, method, url, io.Discard)
return ctx.Response()
// Post registers your function to be called when the given POST path has been requested.
func (s *server) Post(path string, handler Handler) {
s.Router().Add(http.MethodPost, path, handler)
}
// Delete registers your function to be called when the given DELETE path has been requested.
func (s *server) Delete(path string, handler Handler) {
s.Router().Add(http.MethodDelete, path, handler)
}
// Put registers your function to be called when the given PUT path has been requested.
func (s *server) Put(path string, handler Handler) {
s.Router().Add(http.MethodPut, path, handler)
}
// ServeHTTP responds to the given request.
func (s *server) ServeHTTP(res http.ResponseWriter, req *http.Request) {
ctx := s.pool.Get().(*ctx)
ctx.request = request{req}
ctx.response = response{res}
err := s.handlers[0](ctx)
if err != nil {
s.errorHandler(ctx, err)
}
ctx.params = ctx.params[:0]
ctx.handlerCount = 0
s.pool.Put(ctx)
}
// Run starts the server on the given address.
func (s *server) Run(address string) error {
func (server *server) Run(address string) error {
srv := &http.Server{
Addr: address,
Handler: server,
ReadTimeout: server.config.Timeout.Read,
WriteTimeout: server.config.Timeout.Write,
IdleTimeout: server.config.Timeout.Idle,
ReadHeaderTimeout: server.config.Timeout.ReadHeader,
}
listener, err := net.Listen("tcp", address)
if err != nil {
return err
}
defer listener.Close()
go func() {
for {
conn, err := listener.Accept()
if err != nil {
continue
}
go s.handleConnection(conn)
}
}()
go srv.Serve(listener)
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
<-stop
return nil
ctx, cancel := context.WithTimeout(context.Background(), server.config.Timeout.Shutdown)
defer cancel()
return srv.Shutdown(ctx)
}
// Router returns the router used by the server.
func (s *server) Router() *router.Router[Handler] {
return s.router
return &s.router
}
// Use adds handlers to your handlers chain.
@ -114,135 +145,3 @@ func (s *server) Use(handlers ...Handler) {
s.handlers = append(s.handlers[:len(s.handlers)-1], handlers...)
s.handlers = append(s.handlers, last)
}
// handleConnection handles an accepted connection.
func (s *server) handleConnection(conn net.Conn) {
var (
ctx = s.contextPool.Get().(*context)
method string
url string
)
ctx.reader.Reset(conn)
defer conn.Close()
defer s.contextPool.Put(ctx)
for {
// Read the HTTP request line
message, err := ctx.reader.ReadString('\n')
if err != nil {
return
}
space := strings.IndexByte(message, ' ')
if space <= 0 {
io.WriteString(conn, "HTTP/1.1 400 Bad Request\r\n\r\n")
return
}
method = message[:space]
if !isRequestMethod(method) {
io.WriteString(conn, "HTTP/1.1 400 Bad Request\r\n\r\n")
return
}
lastSpace := strings.LastIndexByte(message, ' ')
if lastSpace == space {
lastSpace = len(message) - len("\r\n")
}
url = message[space+1 : lastSpace]
// Add headers until we meet an empty line
for {
message, err = ctx.reader.ReadString('\n')
if err != nil {
return
}
if message == "\r\n" {
break
}
colon := strings.IndexByte(message, ':')
if colon <= 0 {
continue
}
key := message[:colon]
value := message[colon+2 : len(message)-2]
ctx.request.headers = append(ctx.request.headers, Header{
Key: key,
Value: value,
})
}
// Handle the request
s.handleRequest(ctx, method, url, conn)
// Clean up the context
ctx.request.headers = ctx.request.headers[:0]
ctx.request.body = ctx.request.body[:0]
ctx.response.headers = ctx.response.headers[:0]
ctx.response.body = ctx.response.body[:0]
ctx.params = ctx.params[:0]
ctx.handlerCount = 0
ctx.status = 200
}
}
// handleRequest handles the given request.
func (s *server) handleRequest(ctx *context, method string, url string, writer io.Writer) {
ctx.method = method
ctx.scheme, ctx.host, ctx.path, ctx.query = parseURL(url)
err := s.handlers[0](ctx)
if err != nil {
s.errorHandler(ctx, err)
}
tmp := bytes.Buffer{}
tmp.WriteString("HTTP/1.1 ")
tmp.WriteString(strconv.Itoa(int(ctx.status)))
tmp.WriteString("\r\nContent-Length: ")
tmp.WriteString(strconv.Itoa(len(ctx.response.body)))
tmp.WriteString("\r\n")
for _, header := range ctx.response.headers {
tmp.WriteString(header.Key)
tmp.WriteString(": ")
tmp.WriteString(header.Value)
tmp.WriteString("\r\n")
}
tmp.WriteString("\r\n")
tmp.Write(ctx.response.body)
writer.Write(tmp.Bytes())
}
// newContext allocates a new context with the default state.
func (s *server) newContext() *context {
return &context{
server: s,
request: request{
reader: bufio.NewReader(nil),
body: make([]byte, 0),
headers: make([]Header, 0, 8),
params: make([]router.Parameter, 0, 8),
},
response: response{
body: make([]byte, 0, 1024),
headers: make([]Header, 0, 8),
status: 200,
},
}
}

View File

@ -1,9 +1,13 @@
package web_test
import (
"errors"
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
"strings"
"syscall"
"testing"
@ -11,13 +15,178 @@ import (
"git.akyoto.dev/go/web"
)
func TestRouter(t *testing.T) {
s := web.NewServer()
s.Get("/", func(ctx web.Context) error {
return ctx.Bytes([]byte("Hello"))
})
s.Get("/string", func(ctx web.Context) error {
return ctx.String("Hello")
})
s.Get("/write", func(ctx web.Context) error {
_, err := ctx.Response().Write([]byte("Hello"))
return err
})
s.Get("/writestring", func(ctx web.Context) error {
_, err := io.WriteString(ctx.Response(), "Hello")
return err
})
s.Get("/error", func(ctx web.Context) error {
return ctx.Status(http.StatusUnauthorized).Error("Not logged in")
})
s.Get("/error2", func(ctx web.Context) error {
return ctx.Status(http.StatusUnauthorized).Error("Not logged in", errors.New("Missing auth token"))
})
s.Get("/reader", func(ctx web.Context) error {
return ctx.Copy(strings.NewReader("Hello"))
})
s.Get("/file", func(ctx web.Context) error {
return ctx.File("testdata/file.txt")
})
s.Get("/flush", func(ctx web.Context) error {
ctx.Response().WriteString("Hello 1\n")
ctx.Response().WriteString("Hello 2\n")
ctx.Response().Flush()
return nil
})
s.Get("/echo", func(ctx web.Context) error {
return ctx.Copy(ctx.Request())
})
s.Get("/context", func(ctx web.Context) error {
return ctx.Request().Context().Err()
})
s.Get("/redirect", func(ctx web.Context) error {
return ctx.Redirect(http.StatusTemporaryRedirect, "/")
})
s.Get("/request/data", func(ctx web.Context) error {
request := ctx.Request()
method := request.Method()
protocol := request.Protocol()
host := request.Host()
path := request.Path()
return ctx.String(fmt.Sprintf("%s %s %s %s", method, protocol, host, path))
})
s.Get("/request/header", func(ctx web.Context) error {
acceptEncoding := ctx.Request().Header("Accept-Encoding")
return ctx.String(acceptEncoding)
})
s.Get("/response/header", func(ctx web.Context) error {
ctx.Response().SetHeader("Content-Type", "text/plain")
contentType := ctx.Response().Header("Content-Type")
return ctx.String(contentType)
})
s.Get("/blog/:article", func(ctx web.Context) error {
article := ctx.Get("article")
return ctx.String(article)
})
s.Get("/missing-parameter", func(ctx web.Context) error {
missing := ctx.Get("missing")
return ctx.String(missing)
})
s.Get("/scheme", func(ctx web.Context) error {
return ctx.String(ctx.Request().Scheme())
})
s.Post("/", func(ctx web.Context) error {
return ctx.String("Post")
})
s.Delete("/", func(ctx web.Context) error {
return ctx.String("Delete")
})
s.Put("/", func(ctx web.Context) error {
return ctx.String("Put")
})
tests := []struct {
Method string
URL string
Body string
Status int
Response string
}{
{Method: "GET", URL: "/", Body: "", Status: http.StatusOK, Response: "Hello"},
{Method: "GET", URL: "/context", Body: "", Status: http.StatusOK, Response: ""},
{Method: "GET", URL: "/echo", Body: "Echo", Status: http.StatusOK, Response: "Echo"},
{Method: "GET", URL: "/error", Body: "", Status: http.StatusUnauthorized, Response: "Not logged in"},
{Method: "GET", URL: "/error2", Body: "", Status: http.StatusUnauthorized, Response: "Not logged in\nMissing auth token"},
{Method: "GET", URL: "/file", Body: "", Status: http.StatusOK, Response: "Hello File"},
{Method: "GET", URL: "/flush", Body: "", Status: http.StatusOK, Response: "Hello 1\nHello 2\n"},
{Method: "GET", URL: "/not-found", Body: "", Status: http.StatusNotFound, Response: http.StatusText(http.StatusNotFound)},
{Method: "GET", URL: "/request/data", Body: "", Status: http.StatusOK, Response: "GET HTTP/1.1 example.com /request/data"},
{Method: "GET", URL: "/request/header", Body: "", Status: http.StatusOK, Response: ""},
{Method: "GET", URL: "/response/header", Body: "", Status: http.StatusOK, Response: "text/plain"},
{Method: "GET", URL: "/reader", Body: "", Status: http.StatusOK, Response: "Hello"},
{Method: "GET", URL: "/redirect", Body: "", Status: http.StatusTemporaryRedirect, Response: ""},
{Method: "GET", URL: "/string", Body: "", Status: http.StatusOK, Response: "Hello"},
{Method: "GET", URL: "/scheme", Body: "", Status: http.StatusOK, Response: "http"},
{Method: "GET", URL: "/write", Body: "", Status: http.StatusOK, Response: "Hello"},
{Method: "GET", URL: "/writestring", Body: "", Status: http.StatusOK, Response: "Hello"},
{Method: "GET", URL: "/blog/testing-my-router", Body: "", Status: http.StatusOK, Response: "testing-my-router"},
{Method: "GET", URL: "/missing-parameter", Body: "", Status: http.StatusOK, Response: ""},
{Method: "POST", URL: "/", Body: "", Status: http.StatusOK, Response: "Post"},
{Method: "DELETE", URL: "/", Body: "", Status: http.StatusOK, Response: "Delete"},
{Method: "PUT", URL: "/", Body: "", Status: http.StatusOK, Response: "Put"},
}
for _, test := range tests {
t.Run("example.com"+test.URL, func(t *testing.T) {
request := httptest.NewRequest(test.Method, "http://example.com"+test.URL, strings.NewReader(test.Body))
response := httptest.NewRecorder()
s.ServeHTTP(response, request)
result := response.Result()
assert.Equal(t, result.StatusCode, test.Status)
body, err := io.ReadAll(result.Body)
assert.Nil(t, err)
assert.Equal(t, string(body), test.Response)
})
}
}
func TestMiddleware(t *testing.T) {
s := web.NewServer()
s.Use(func(ctx web.Context) error {
ctx.Response().SetHeader("Middleware", "true")
return ctx.Next()
})
request := httptest.NewRequest(http.MethodGet, "/", nil)
response := httptest.NewRecorder()
s.ServeHTTP(response, request)
assert.Equal(t, response.Header().Get("Middleware"), "true")
}
func TestPanic(t *testing.T) {
s := web.NewServer()
s.Get("/panic", func(ctx web.Context) error {
s.Router().Add(http.MethodGet, "/panic", func(ctx web.Context) error {
panic("Something unbelievable happened")
})
t.Run("example.com/panic", func(t *testing.T) {
defer func() {
r := recover()
@ -26,129 +195,19 @@ func TestPanic(t *testing.T) {
}
}()
s.Request("GET", "/panic", nil, nil)
request := httptest.NewRequest(http.MethodGet, "/panic", nil)
response := httptest.NewRecorder()
s.ServeHTTP(response, request)
})
}
func TestRun(t *testing.T) {
s := web.NewServer()
go func() {
defer syscall.Kill(syscall.Getpid(), syscall.SIGTERM)
_, err := http.Get("http://127.0.0.1:8080/")
assert.Nil(t, err)
}()
s.Run(":8080")
}
func TestBadRequest(t *testing.T) {
s := web.NewServer()
go func() {
defer syscall.Kill(syscall.Getpid(), syscall.SIGTERM)
conn, err := net.Dial("tcp", ":8080")
assert.Nil(t, err)
defer conn.Close()
_, err = io.WriteString(conn, "BadRequest\r\n\r\n")
assert.Nil(t, err)
response, err := io.ReadAll(conn)
assert.Nil(t, err)
assert.Equal(t, string(response), "HTTP/1.1 400 Bad Request\r\n\r\n")
}()
s.Run(":8080")
}
func TestBadRequestHeader(t *testing.T) {
s := web.NewServer()
s.Get("/", func(ctx web.Context) error {
return ctx.String("Hello")
})
go func() {
defer syscall.Kill(syscall.Getpid(), syscall.SIGTERM)
conn, err := net.Dial("tcp", ":8080")
assert.Nil(t, err)
defer conn.Close()
_, err = io.WriteString(conn, "GET / HTTP/1.1\r\nBadHeader\r\nGood: Header\r\n\r\n")
assert.Nil(t, err)
buffer := make([]byte, len("HTTP/1.1 200"))
_, err = conn.Read(buffer)
assert.Nil(t, err)
assert.Equal(t, string(buffer), "HTTP/1.1 200")
}()
s.Run(":8080")
}
func TestBadRequestMethod(t *testing.T) {
s := web.NewServer()
go func() {
defer syscall.Kill(syscall.Getpid(), syscall.SIGTERM)
conn, err := net.Dial("tcp", ":8080")
assert.Nil(t, err)
defer conn.Close()
_, err = io.WriteString(conn, "BAD-METHOD / HTTP/1.1\r\n\r\n")
assert.Nil(t, err)
response, err := io.ReadAll(conn)
assert.Nil(t, err)
assert.Equal(t, string(response), "HTTP/1.1 400 Bad Request\r\n\r\n")
}()
s.Run(":8080")
}
func TestBadRequestProtocol(t *testing.T) {
s := web.NewServer()
s.Get("/", func(ctx web.Context) error {
return ctx.String("Hello")
})
go func() {
defer syscall.Kill(syscall.Getpid(), syscall.SIGTERM)
conn, err := net.Dial("tcp", ":8080")
assert.Nil(t, err)
defer conn.Close()
_, err = io.WriteString(conn, "GET /\r\n\r\n")
assert.Nil(t, err)
buffer := make([]byte, len("HTTP/1.1 200"))
_, err = conn.Read(buffer)
assert.Nil(t, err)
assert.Equal(t, string(buffer), "HTTP/1.1 200")
}()
s.Run(":8080")
}
func TestEarlyClose(t *testing.T) {
s := web.NewServer()
go func() {
defer syscall.Kill(syscall.Getpid(), syscall.SIGTERM)
conn, err := net.Dial("tcp", ":8080")
assert.Nil(t, err)
_, err = io.WriteString(conn, "GET /\r\n")
assert.Nil(t, err)
err = conn.Close()
err = syscall.Kill(syscall.Getpid(), syscall.SIGTERM)
assert.Nil(t, err)
}()

63
benchmarks_test.go Normal file
View File

@ -0,0 +1,63 @@
package web_test
import (
"net/http/httptest"
"strings"
"testing"
"git.akyoto.dev/go/router/testdata"
"git.akyoto.dev/go/web"
)
func BenchmarkStatic(b *testing.B) {
paths := []string{
"/",
"/hello",
"/hello/world",
}
s := web.NewServer()
for _, path := range paths {
s.Get(path, func(ctx web.Context) error {
return ctx.String("Hello")
})
}
for _, path := range paths {
b.Run(strings.TrimPrefix(path, "/"), func(b *testing.B) {
request := httptest.NewRequest("GET", path, nil)
response := &NullResponse{}
for range b.N {
s.ServeHTTP(response, request)
}
})
}
}
func BenchmarkGitHub(b *testing.B) {
paths := []string{
"/gists/:id",
"/repos/:a/:b",
}
s := web.NewServer()
for _, route := range testdata.Routes("testdata/github.txt") {
s.Router().Add(route.Method, route.Path, func(ctx web.Context) error {
return ctx.String("Hello")
})
}
for _, path := range paths {
b.Run(strings.TrimPrefix(path, "/"), func(b *testing.B) {
request := httptest.NewRequest("GET", path, nil)
response := &NullResponse{}
for range b.N {
s.ServeHTTP(response, request)
}
})
}
}

12
common_test.go Normal file
View File

@ -0,0 +1,12 @@
package web_test
import "net/http"
// NullResponse implements the http.ResponseWriter interface with
// empty methods to better understand memory usage in benchmarks.
type NullResponse struct{}
func (r *NullResponse) Header() http.Header { return nil }
func (r *NullResponse) Write([]byte) (int, error) { return 0, nil }
func (r *NullResponse) WriteString(string) (int, error) { return 0, nil }
func (r *NullResponse) WriteHeader(int) {}

30
config.go Normal file
View File

@ -0,0 +1,30 @@
package web
import "time"
// config represents the server configuration.
type config struct {
Timeout timeoutConfig `json:"timeout"`
}
// timeoutConfig lets you configure the different timeout durations.
type timeoutConfig struct {
Idle time.Duration `json:"idle"`
Read time.Duration `json:"read"`
ReadHeader time.Duration `json:"readHeader"`
Write time.Duration `json:"write"`
Shutdown time.Duration `json:"shutdown"`
}
// Reset resets all fields to the default configuration.
func defaultConfig() config {
return config{
Timeout: timeoutConfig{
Idle: 3 * time.Minute,
Write: 2 * time.Minute,
Read: 5 * time.Second,
ReadHeader: 5 * time.Second,
Shutdown: 250 * time.Millisecond,
},
}
}

View File

@ -1,4 +1,4 @@
package send
package content
import (
"encoding/json"

80
content/content_test.go Normal file
View File

@ -0,0 +1,80 @@
package content_test
import (
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"git.akyoto.dev/go/assert"
"git.akyoto.dev/go/web"
"git.akyoto.dev/go/web/content"
)
func TestContentTypes(t *testing.T) {
s := web.NewServer()
s.Get("/css", func(ctx web.Context) error {
return content.CSS(ctx, "body{}")
})
s.Get("/csv", func(ctx web.Context) error {
return content.CSV(ctx, "ID;Name\n")
})
s.Get("/html", func(ctx web.Context) error {
return content.HTML(ctx, "<html></html>")
})
s.Get("/js", func(ctx web.Context) error {
return content.JS(ctx, "console.log(42)")
})
s.Get("/json", func(ctx web.Context) error {
return content.JSON(ctx, struct{ Name string }{Name: "User 1"})
})
s.Get("/text", func(ctx web.Context) error {
return content.Text(ctx, "Hello")
})
s.Get("/xml", func(ctx web.Context) error {
return content.XML(ctx, "<xml></xml>")
})
tests := []struct {
Method string
URL string
Body string
Status int
Response string
ContentType string
}{
{Method: "GET", URL: "/css", Body: "", Status: http.StatusOK, Response: "body{}", ContentType: "text/css"},
{Method: "GET", URL: "/csv", Body: "", Status: http.StatusOK, Response: "ID;Name\n", ContentType: "text/csv"},
{Method: "GET", URL: "/html", Body: "", Status: http.StatusOK, Response: "<html></html>", ContentType: "text/html"},
{Method: "GET", URL: "/js", Body: "", Status: http.StatusOK, Response: "console.log(42)", ContentType: "text/javascript"},
{Method: "GET", URL: "/json", Body: "", Status: http.StatusOK, Response: "{\"Name\":\"User 1\"}\n", ContentType: "application/json"},
{Method: "GET", URL: "/text", Body: "", Status: http.StatusOK, Response: "Hello", ContentType: "text/plain"},
{Method: "GET", URL: "/xml", Body: "", Status: http.StatusOK, Response: "<xml></xml>", ContentType: "text/xml"},
}
for _, test := range tests {
t.Run("example.com"+test.URL, func(t *testing.T) {
request := httptest.NewRequest(test.Method, "http://example.com"+test.URL, strings.NewReader(test.Body))
response := httptest.NewRecorder()
s.ServeHTTP(response, request)
result := response.Result()
assert.Equal(t, result.StatusCode, test.Status)
contentType := result.Header.Get("Content-Type")
assert.Equal(t, contentType, test.ContentType)
body, err := io.ReadAll(result.Body)
assert.Nil(t, err)
assert.Equal(t, string(body), test.Response)
})
}
}

24
examples/logger/main.go Normal file
View File

@ -0,0 +1,24 @@
package main
import (
"fmt"
"time"
"git.akyoto.dev/go/web"
)
func main() {
s := web.NewServer()
s.Use(func(ctx web.Context) error {
start := time.Now()
defer func() {
fmt.Println(ctx.Request().Path(), time.Since(start))
}()
return ctx.Next()
})
s.Run(":8080")
}

28
examples/stream/main.go Normal file
View File

@ -0,0 +1,28 @@
package main
import (
"time"
"git.akyoto.dev/go/web"
)
func main() {
s := web.NewServer()
s.Get("/", func(ctx web.Context) error {
ticker := time.NewTicker(time.Second)
for {
select {
case <-ctx.Request().Context().Done():
return nil
case <-ticker.C:
ctx.Response().WriteString("Hello\n")
ctx.Response().Flush()
}
}
})
s.Run(":8080")
}

41
http.go
View File

@ -1,41 +0,0 @@
package web
import "strings"
// isRequestMethod returns true if the given string is a valid HTTP request method.
func isRequestMethod(method string) bool {
switch method {
case "GET", "HEAD", "POST", "PUT", "DELETE", "CONNECT", "OPTIONS", "TRACE", "PATCH":
return true
default:
return false
}
}
// parseURL parses a URL and returns the scheme, host, path and query.
func parseURL(url string) (scheme string, host string, path string, query string) {
schemePos := strings.Index(url, "://")
if schemePos != -1 {
scheme = url[:schemePos]
url = url[schemePos+len("://"):]
}
pathPos := strings.IndexByte(url, '/')
if pathPos != -1 {
host = url[:pathPos]
url = url[pathPos:]
}
queryPos := strings.IndexByte(url, '?')
if queryPos != -1 {
path = url[:queryPos]
query = url[queryPos+1:]
return
}
path = url
return
}

View File

@ -1,67 +0,0 @@
package send_test
import (
"testing"
"git.akyoto.dev/go/assert"
"git.akyoto.dev/go/web"
"git.akyoto.dev/go/web/send"
)
func TestContentTypes(t *testing.T) {
s := web.NewServer()
s.Get("/css", func(ctx web.Context) error {
return send.CSS(ctx, "body{}")
})
s.Get("/csv", func(ctx web.Context) error {
return send.CSV(ctx, "ID;Name\n")
})
s.Get("/html", func(ctx web.Context) error {
return send.HTML(ctx, "<html></html>")
})
s.Get("/js", func(ctx web.Context) error {
return send.JS(ctx, "console.log(42)")
})
s.Get("/json", func(ctx web.Context) error {
return send.JSON(ctx, struct{ Name string }{Name: "User 1"})
})
s.Get("/text", func(ctx web.Context) error {
return send.Text(ctx, "Hello")
})
s.Get("/xml", func(ctx web.Context) error {
return send.XML(ctx, "<xml></xml>")
})
tests := []struct {
Method string
URL string
Body string
Status int
Response string
ContentType string
}{
{Method: "GET", URL: "/css", Status: 200, Response: "body{}", ContentType: "text/css"},
{Method: "GET", URL: "/csv", Status: 200, Response: "ID;Name\n", ContentType: "text/csv"},
{Method: "GET", URL: "/html", Status: 200, Response: "<html></html>", ContentType: "text/html"},
{Method: "GET", URL: "/js", Status: 200, Response: "console.log(42)", ContentType: "text/javascript"},
{Method: "GET", URL: "/json", Status: 200, Response: "{\"Name\":\"User 1\"}\n", ContentType: "application/json"},
{Method: "GET", URL: "/text", Status: 200, Response: "Hello", ContentType: "text/plain"},
{Method: "GET", URL: "/xml", Status: 200, Response: "<xml></xml>", ContentType: "text/xml"},
}
for _, test := range tests {
t.Run(test.URL, func(t *testing.T) {
response := s.Request(test.Method, "http://example.com"+test.URL, nil, nil)
assert.Equal(t, response.Status(), test.Status)
assert.Equal(t, response.Header("Content-Type"), test.ContentType)
assert.Equal(t, string(response.Body()), test.Response)
})
}
}

1
testdata/file.txt vendored Normal file
View File

@ -0,0 +1 @@
Hello File

203
testdata/github.txt vendored Normal file
View File

@ -0,0 +1,203 @@
GET /authorizations
GET /authorizations/:id
POST /authorizations
DELETE /authorizations/:id
GET /applications/:client_id/tokens/:access_token
DELETE /applications/:client_id/tokens
DELETE /applications/:client_id/tokens/:access_token
GET /events
GET /repos/:owner/:repo/events
GET /networks/:owner/:repo/events
GET /orgs/:org/events
GET /users/:user/received_events
GET /users/:user/received_events/public
GET /users/:user/events
GET /users/:user/events/public
GET /users/:user/events/orgs/:org
GET /feeds
GET /notifications
GET /repos/:owner/:repo/notifications
PUT /notifications
PUT /repos/:owner/:repo/notifications
GET /notifications/threads/:id
GET /notifications/threads/:id/subscription
PUT /notifications/threads/:id/subscription
DELETE /notifications/threads/:id/subscription
GET /repos/:owner/:repo/stargazers
GET /users/:user/starred
GET /user/starred
GET /user/starred/:owner/:repo
PUT /user/starred/:owner/:repo
DELETE /user/starred/:owner/:repo
GET /repos/:owner/:repo/subscribers
GET /users/:user/subscriptions
GET /user/subscriptions
GET /repos/:owner/:repo/subscription
PUT /repos/:owner/:repo/subscription
DELETE /repos/:owner/:repo/subscription
GET /user/subscriptions/:owner/:repo
PUT /user/subscriptions/:owner/:repo
DELETE /user/subscriptions/:owner/:repo
GET /users/:user/gists
GET /gists
GET /gists/:id
POST /gists
PUT /gists/:id/star
DELETE /gists/:id/star
GET /gists/:id/star
POST /gists/:id/forks
DELETE /gists/:id
GET /repos/:owner/:repo/git/blobs/:sha
POST /repos/:owner/:repo/git/blobs
GET /repos/:owner/:repo/git/commits/:sha
POST /repos/:owner/:repo/git/commits
GET /repos/:owner/:repo/git/refs
POST /repos/:owner/:repo/git/refs
GET /repos/:owner/:repo/git/tags/:sha
POST /repos/:owner/:repo/git/tags
GET /repos/:owner/:repo/git/trees/:sha
POST /repos/:owner/:repo/git/trees
GET /issues
GET /user/issues
GET /orgs/:org/issues
GET /repos/:owner/:repo/issues
GET /repos/:owner/:repo/issues/:number
POST /repos/:owner/:repo/issues
GET /repos/:owner/:repo/assignees
GET /repos/:owner/:repo/assignees/:assignee
GET /repos/:owner/:repo/issues/:number/comments
POST /repos/:owner/:repo/issues/:number/comments
GET /repos/:owner/:repo/issues/:number/events
GET /repos/:owner/:repo/labels
GET /repos/:owner/:repo/labels/:name
POST /repos/:owner/:repo/labels
DELETE /repos/:owner/:repo/labels/:name
GET /repos/:owner/:repo/issues/:number/labels
POST /repos/:owner/:repo/issues/:number/labels
DELETE /repos/:owner/:repo/issues/:number/labels/:name
PUT /repos/:owner/:repo/issues/:number/labels
DELETE /repos/:owner/:repo/issues/:number/labels
GET /repos/:owner/:repo/milestones/:number/labels
GET /repos/:owner/:repo/milestones
GET /repos/:owner/:repo/milestones/:number
POST /repos/:owner/:repo/milestones
DELETE /repos/:owner/:repo/milestones/:number
GET /emojis
GET /gitignore/templates
GET /gitignore/templates/:name
POST /markdown
POST /markdown/raw
GET /meta
GET /rate_limit
GET /users/:user/orgs
GET /user/orgs
GET /orgs/:org
GET /orgs/:org/members
GET /orgs/:org/members/:user
DELETE /orgs/:org/members/:user
GET /orgs/:org/public_members
GET /orgs/:org/public_members/:user
PUT /orgs/:org/public_members/:user
DELETE /orgs/:org/public_members/:user
GET /orgs/:org/teams
GET /teams/:id
POST /orgs/:org/teams
DELETE /teams/:id
GET /teams/:id/members
GET /teams/:id/members/:user
PUT /teams/:id/members/:user
DELETE /teams/:id/members/:user
GET /teams/:id/repos
GET /teams/:id/repos/:owner/:repo
PUT /teams/:id/repos/:owner/:repo
DELETE /teams/:id/repos/:owner/:repo
GET /user/teams
GET /repos/:owner/:repo/pulls
GET /repos/:owner/:repo/pulls/:number
POST /repos/:owner/:repo/pulls
GET /repos/:owner/:repo/pulls/:number/commits
GET /repos/:owner/:repo/pulls/:number/files
GET /repos/:owner/:repo/pulls/:number/merge
PUT /repos/:owner/:repo/pulls/:number/merge
GET /repos/:owner/:repo/pulls/:number/comments
PUT /repos/:owner/:repo/pulls/:number/comments
GET /user/repos
GET /users/:user/repos
GET /orgs/:org/repos
GET /repositories
POST /user/repos
POST /orgs/:org/repos
GET /repos/:owner/:repo
GET /repos/:owner/:repo/contributors
GET /repos/:owner/:repo/languages
GET /repos/:owner/:repo/teams
GET /repos/:owner/:repo/tags
GET /repos/:owner/:repo/branches
GET /repos/:owner/:repo/branches/:branch
DELETE /repos/:owner/:repo
GET /repos/:owner/:repo/collaborators
GET /repos/:owner/:repo/collaborators/:user
PUT /repos/:owner/:repo/collaborators/:user
DELETE /repos/:owner/:repo/collaborators/:user
GET /repos/:owner/:repo/comments
GET /repos/:owner/:repo/commits/:sha/comments
POST /repos/:owner/:repo/commits/:sha/comments
GET /repos/:owner/:repo/comments/:id
DELETE /repos/:owner/:repo/comments/:id
GET /repos/:owner/:repo/commits
GET /repos/:owner/:repo/commits/:sha
GET /repos/:owner/:repo/readme
GET /repos/:owner/:repo/keys
GET /repos/:owner/:repo/keys/:id
POST /repos/:owner/:repo/keys
DELETE /repos/:owner/:repo/keys/:id
GET /repos/:owner/:repo/downloads
GET /repos/:owner/:repo/downloads/:id
DELETE /repos/:owner/:repo/downloads/:id
GET /repos/:owner/:repo/forks
POST /repos/:owner/:repo/forks
GET /repos/:owner/:repo/hooks
GET /repos/:owner/:repo/hooks/:id
POST /repos/:owner/:repo/hooks
POST /repos/:owner/:repo/hooks/:id/tests
DELETE /repos/:owner/:repo/hooks/:id
POST /repos/:owner/:repo/merges
GET /repos/:owner/:repo/releases
GET /repos/:owner/:repo/releases/:id
POST /repos/:owner/:repo/releases
DELETE /repos/:owner/:repo/releases/:id
GET /repos/:owner/:repo/releases/:id/assets
GET /repos/:owner/:repo/stats/contributors
GET /repos/:owner/:repo/stats/commit_activity
GET /repos/:owner/:repo/stats/code_frequency
GET /repos/:owner/:repo/stats/participation
GET /repos/:owner/:repo/stats/punch_card
GET /repos/:owner/:repo/statuses/:ref
POST /repos/:owner/:repo/statuses/:ref
GET /search/repositories
GET /search/code
GET /search/issues
GET /search/users
GET /legacy/issues/search/:owner/:repository/:state/:keyword
GET /legacy/repos/search/:keyword
GET /legacy/user/search/:keyword
GET /legacy/user/email/:email
GET /users/:user
GET /user
GET /users
GET /user/emails
POST /user/emails
DELETE /user/emails
GET /users/:user/followers
GET /user/followers
GET /users/:user/following
GET /user/following
GET /user/following/:user
GET /users/:user/following/:target_user
PUT /user/following/:user
DELETE /user/following/:user
GET /users/:user/keys
GET /user/keys
GET /user/keys/:id
POST /user/keys
DELETE /user/keys/:id