Skip to content

Commit

Permalink
feat: api serve (#98)
Browse files Browse the repository at this point in the history
  • Loading branch information
abemedia authored May 7, 2023
1 parent fe7c7eb commit 602b24c
Showing 1 changed file with 21 additions and 9 deletions.
30 changes: 21 additions & 9 deletions api.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,19 @@ package don

import (
"bytes"
"net"
"net/http"

"github.com/abemedia/httprouter"
"github.com/valyala/fasthttp"
)

// Empty is the type used when an API handler contains either no request or no
// response.
type Empty struct{}

// DefaultEncoding contains the mime type of the default encoding to fall
// back on if no `Accept` or `Content-Type` header was provided.
var DefaultEncoding = "text/plain"

type Middleware func(fasthttp.RequestHandler) fasthttp.RequestHandler
Expand Down Expand Up @@ -38,6 +43,8 @@ type API struct {
}

type Config struct {
// DefaultEncoding contains the mime type of the default encoding to fall
// back on if no `Accept` or `Content-Type` header was provided.
DefaultEncoding string

// DisableNoContent controls whether a nil or zero value response should
Expand All @@ -55,10 +62,8 @@ func New(c *Config) *API {
c.DefaultEncoding = DefaultEncoding
}

r := httprouter.New()

return &API{
router: r,
router: httprouter.New(),
config: c,
NotFound: E(ErrNotFound),
MethodNotAllowed: E(ErrMethodNotAllowed),
Expand Down Expand Up @@ -102,7 +107,7 @@ func (r *API) Handler(method, path string, handle http.Handler) {

// HandlerFunc is an adapter which allows the usage of an http.HandlerFunc as a request handle.
func (r *API) HandleFunc(method, path string, handle http.HandlerFunc) {
r.Handler(method, path, handle)
r.router.HandlerFunc(method, path, handle)
}

func (r *API) Group(path string) Router {
Expand All @@ -124,8 +129,6 @@ func (r *API) RequestHandler() fasthttp.RequestHandler {
h = mw(h)
}

anyEncoding := []byte("*/*")

return func(ctx *fasthttp.RequestCtx) {
ct := ctx.Request.Header.ContentType()
if len(ct) == 0 || bytes.HasPrefix(ct, anyEncoding) {
Expand Down Expand Up @@ -156,11 +159,20 @@ func (r *API) RequestHandler() fasthttp.RequestHandler {

// ListenAndServe serves HTTP requests from the given TCP4 addr.
func (r *API) ListenAndServe(addr string) error {
s := &fasthttp.Server{
return newServer(r).ListenAndServe(addr)
}

// Serve serves incoming connections from the given listener.
func (r *API) Serve(ln net.Listener) error {
return newServer(r).Serve(ln)
}

func newServer(r *API) *fasthttp.Server {
return &fasthttp.Server{
Handler: r.RequestHandler(),
StreamRequestBody: true,
NoDefaultContentType: true,
}

return s.ListenAndServe(addr)
}

var anyEncoding = []byte("*/*")

0 comments on commit 602b24c

Please sign in to comment.