Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: echo transport #7

Merged
merged 2 commits into from
Jul 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions go.work
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ go 1.21.6
use (
./core
./example
./transport/echo
./transport/http
./transport/jetstream
)
5 changes: 3 additions & 2 deletions go.work.sum
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
github.com/kikihakiem/gkit/transport/http v0.4.0/go.mod h1:EYkrYOEhjhUybgnT8BfpophqnYpuro/wu/d/wXDRKO0=
github.com/kikihakiem/gkit/transport/jetstream v0.3.0/go.mod h1:NIiGOWXz6C0SzZfWCG8c/QXg2NcZuVlZv/peLmNmt5A=
github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
go.etcd.io/gofail v0.1.0/go.mod h1:VZBCXYGZhHAinaBiiqYvuDynvahNsAyLFwB3kEHKz1M=
go.uber.org/automaxprocs v1.5.3/go.mod h1:eRbA25aqJrxAbsLO0xy5jVwPt7FQnRgjW+efnwa1WM0=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
golang.org/x/term v0.16.0/go.mod h1:yn7UURbUtPyrVJPGPq404EukNFxcm/foM+bV/bfcDsY=
golang.org/x/term v0.19.0/go.mod h1:2CuTdWZ7KHSQwUzKva0cbMg6q2DMI3Mmxp+gKJbskEk=
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
2 changes: 2 additions & 0 deletions transport/echo/doc.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// package echo provides a general purpose HTTP binding for gkit.Endpoint.
package echo
13 changes: 13 additions & 0 deletions transport/echo/encode_decode.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package echo

import (
"context"

"github.com/labstack/echo/v4"
)

// EncodeResponseFunc encodes the passed response object to the HTTP response
// writer. It's designed to be used in HTTP servers, for server-side
// endpoints. One straightforward EncodeResponseFunc could be something that
// JSON encodes the object directly to the response body.
type EncodeResponseFunc[Res any] func(context.Context, echo.Context, Res) error
36 changes: 36 additions & 0 deletions transport/echo/example_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
//go:build unit

package echo_test

import (
"context"
"net/http"
"net/http/httptest"
"testing"

echotransport "github.com/kikihakiem/gkit/transport/echo"
"github.com/labstack/echo/v4"
"github.com/stretchr/testify/assert"
)

func TestPopulateRequestContext(t *testing.T) {
handler := echotransport.NewHandler(
func(ctx context.Context, request struct{}) (response struct{}, err error) {
assert.Equal(t, http.MethodPatch, ctx.Value(echotransport.ContextKeyRequestMethod).(string))
assert.Equal(t, "/search", ctx.Value(echotransport.ContextKeyRequestPath).(string))
assert.Equal(t, "/search?q=sympatico", ctx.Value(echotransport.ContextKeyRequestURI).(string))
assert.Equal(t, "a1b2c3d4e5", ctx.Value(echotransport.ContextKeyRequestXRequestID).(string))
return struct{}{}, nil
},
func(context.Context, echo.Context) (struct{}, error) { return struct{}{}, nil },
func(context.Context, echo.Context, struct{}) error { return nil },
echotransport.ServerBefore[struct{}, struct{}](echotransport.PopulateRequestContext),
)

e := echo.New()
req := httptest.NewRequest(http.MethodPatch, "/search?q=sympatico", nil)
req.Header.Set("X-Request-Id", "a1b2c3d4e5")
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
handler.Handle(c)
}
21 changes: 21 additions & 0 deletions transport/echo/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
module github.com/kikihakiem/gkit/transport/echo

go 1.21.6

require (
github.com/kikihakiem/gkit/core v0.4.0
github.com/kikihakiem/gkit/transport/http v0.5.0
github.com/labstack/echo/v4 v4.12.0
)

require (
github.com/labstack/gommon v0.4.2 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/valyala/fasttemplate v1.2.2 // indirect
golang.org/x/crypto v0.22.0 // indirect
golang.org/x/net v0.24.0 // indirect
golang.org/x/sys v0.19.0 // indirect
golang.org/x/text v0.14.0 // indirect
)
35 changes: 35 additions & 0 deletions transport/echo/go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/kikihakiem/gkit/core v0.4.0 h1:NHiKDWJXkBGT2ZBd+n5vaK/iBa9aBCC1/cdZzeZYl3c=
github.com/kikihakiem/gkit/core v0.4.0/go.mod h1:PjK77BVx0+eVzPqx4U9I0FT0ljRSenyKBDiM5KO4/oY=
github.com/kikihakiem/gkit/transport/http v0.5.0 h1:n4FakQrRMi8++ofUPSB/uCnRcMg1MYE4eK2Rto30i9A=
github.com/kikihakiem/gkit/transport/http v0.5.0/go.mod h1:EYkrYOEhjhUybgnT8BfpophqnYpuro/wu/d/wXDRKO0=
github.com/labstack/echo/v4 v4.12.0 h1:IKpw49IMryVB2p1a4dzwlhP1O2Tf2E0Ir/450lH+kI0=
github.com/labstack/echo/v4 v4.12.0/go.mod h1:UP9Cr2DJXbOK3Kr9ONYzNowSh7HP0aG0ShAyycHSJvM=
github.com/labstack/gommon v0.4.2 h1:F8qTUNXgG1+6WQmqoUWnz8WiEU60mXVVw0P4ht1WRA0=
github.com/labstack/gommon v0.4.2/go.mod h1:QlUFxVM+SNXhDL/Z7YhocGIBYOiwB0mXm1+1bAPHPyU=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo=
github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
golang.org/x/crypto v0.22.0 h1:g1v0xeRhjcugydODzvb3mEM9SQ0HGp9s/nh3COQ/C30=
golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M=
golang.org/x/net v0.24.0 h1:1PcaxkF854Fu3+lvBIx5SYn9wRlBzzcnHZSiaFFAb0w=
golang.org/x/net v0.24.0/go.mod h1:2Q7sJY5mzlzWjKtYUEXSlBWCdyaioyXzRB2RtU8KVE8=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o=
golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
133 changes: 133 additions & 0 deletions transport/echo/request_response_funcs.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
package echo

import (
"context"

"github.com/labstack/echo/v4"
)

// RequestFunc may take information from an HTTP request and put it into a
// request context. In Servers, RequestFuncs are executed prior to invoking the
// endpoint.
type RequestFunc func(context.Context, echo.Context) context.Context

// ServerResponseFunc may take information from a request context and use it to
// manipulate a ResponseWriter. ServerResponseFuncs are only executed in
// servers, after invoking the endpoint but prior to writing a response.
type ServerResponseFunc func(context.Context, echo.Context) context.Context

// ClientResponseFunc may take information from an HTTP request and make the
// response available for consumption. ClientResponseFuncs are only executed in
// clients, after a request has been made, but prior to it being decoded.
type ClientResponseFunc func(context.Context, echo.Context) context.Context

// SetContentType returns a ServerResponseFunc that sets the Content-Type header
// to the provided value.
func SetContentType(contentType string) ServerResponseFunc {
return SetResponseHeader("Content-Type", contentType)
}

// SetResponseHeader returns a ServerResponseFunc that sets the given header.
func SetResponseHeader(key, val string) ServerResponseFunc {
return func(ctx context.Context, c echo.Context) context.Context {
c.Response().Header().Set(key, val)
return ctx
}
}

// SetRequestHeader returns a RequestFunc that sets the given header.
func SetRequestHeader(key, val string) RequestFunc {
return func(ctx context.Context, c echo.Context) context.Context {
c.Request().Header.Set(key, val)
return ctx
}
}

// PopulateRequestContext is a RequestFunc that populates several values into
// the context from the HTTP request. Those values may be extracted using the
// corresponding ContextKey type in this package.
func PopulateRequestContext(ctx context.Context, c echo.Context) context.Context {
for k, v := range map[contextKey]string{
ContextKeyRequestMethod: c.Request().Method,
ContextKeyRequestURI: c.Request().RequestURI,
ContextKeyRequestPath: c.Request().URL.Path,
ContextKeyRequestProto: c.Request().Proto,
ContextKeyRequestHost: c.Request().Host,
ContextKeyRequestRemoteAddr: c.Request().RemoteAddr,
ContextKeyRequestXForwardedFor: c.Request().Header.Get("X-Forwarded-For"),
ContextKeyRequestXForwardedProto: c.Request().Header.Get("X-Forwarded-Proto"),
ContextKeyRequestAuthorization: c.Request().Header.Get("Authorization"),
ContextKeyRequestReferer: c.Request().Header.Get("Referer"),
ContextKeyRequestUserAgent: c.Request().Header.Get("User-Agent"),
ContextKeyRequestXRequestID: c.Request().Header.Get("X-Request-Id"),
ContextKeyRequestAccept: c.Request().Header.Get("Accept"),
} {
ctx = context.WithValue(ctx, k, v)
}
return ctx
}

type contextKey int

const (
// ContextKeyRequestMethod is populated in the context by
// PopulateRequestContext. Its value is r.Method.
ContextKeyRequestMethod contextKey = iota

// ContextKeyRequestURI is populated in the context by
// PopulateRequestContext. Its value is r.RequestURI.
ContextKeyRequestURI

// ContextKeyRequestPath is populated in the context by
// PopulateRequestContext. Its value is r.URL.Path.
ContextKeyRequestPath

// ContextKeyRequestProto is populated in the context by
// PopulateRequestContext. Its value is r.Proto.
ContextKeyRequestProto

// ContextKeyRequestHost is populated in the context by
// PopulateRequestContext. Its value is r.Host.
ContextKeyRequestHost

// ContextKeyRequestRemoteAddr is populated in the context by
// PopulateRequestContext. Its value is r.RemoteAddr.
ContextKeyRequestRemoteAddr

// ContextKeyRequestXForwardedFor is populated in the context by
// PopulateRequestContext. Its value is r.Header.Get("X-Forwarded-For").
ContextKeyRequestXForwardedFor

// ContextKeyRequestXForwardedProto is populated in the context by
// PopulateRequestContext. Its value is r.Header.Get("X-Forwarded-Proto").
ContextKeyRequestXForwardedProto

// ContextKeyRequestAuthorization is populated in the context by
// PopulateRequestContext. Its value is r.Header.Get("Authorization").
ContextKeyRequestAuthorization

// ContextKeyRequestReferer is populated in the context by
// PopulateRequestContext. Its value is r.Header.Get("Referer").
ContextKeyRequestReferer

// ContextKeyRequestUserAgent is populated in the context by
// PopulateRequestContext. Its value is r.Header.Get("User-Agent").
ContextKeyRequestUserAgent

// ContextKeyRequestXRequestID is populated in the context by
// PopulateRequestContext. Its value is r.Header.Get("X-Request-Id").
ContextKeyRequestXRequestID

// ContextKeyRequestAccept is populated in the context by
// PopulateRequestContext. Its value is r.Header.Get("Accept").
ContextKeyRequestAccept

// ContextKeyResponseHeaders is populated in the context whenever a
// ServerFinalizerFunc is specified. Its value is of type http.Header, and
// is captured only once the entire response has been written.
ContextKeyResponseHeaders

// ContextKeyResponseSize is populated in the context whenever a
// ServerFinalizerFunc is specified. Its value is of type int64.
ContextKeyResponseSize
)
59 changes: 59 additions & 0 deletions transport/echo/request_response_funcs_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
//go:build unit

package echo_test

import (
"context"
"net/http"
"net/http/httptest"
"testing"

echotransport "github.com/kikihakiem/gkit/transport/echo"
"github.com/labstack/echo/v4"
)

func TestSetResponseHeader(t *testing.T) {
const (
key = "X-Foo"
val = "12345"
)

req := httptest.NewRequest(http.MethodPost, "/dummy", nil)
rec := httptest.NewRecorder()

e := echo.New()
c := e.NewContext(req, rec)

echotransport.SetResponseHeader(key, val)(context.Background(), c)
if want, have := val, c.Response().Header().Get(key); want != have {
t.Errorf("want %q, have %q", want, have)
}
}

func TestSetContentType(t *testing.T) {
const contentType = echo.MIMEApplicationJSON
req := httptest.NewRequest(http.MethodPost, "/dummy", nil)
rec := httptest.NewRecorder()

e := echo.New()
c := e.NewContext(req, rec)

echotransport.SetContentType(contentType)(context.Background(), c)
if want, have := contentType, c.Response().Header().Get("Content-Type"); want != have {
t.Errorf("want %q, have %q", want, have)
}
}

func TestSetRequestHeader(t *testing.T) {
const contentType = echo.MIMEApplicationJSON
req := httptest.NewRequest(http.MethodPost, "/dummy", nil)
rec := httptest.NewRecorder()

e := echo.New()
c := e.NewContext(req, rec)

echotransport.SetRequestHeader(echo.HeaderAccept, echo.MIMEApplicationJSON)(context.Background(), c)
if want, have := contentType, c.Request().Header.Get("Accept"); want != have {
t.Errorf("want %q, have %q", want, have)
}
}
Loading
Loading