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: add example for ResponseFilter #91

Merged
merged 5 commits into from
Jun 21, 2022
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
79 changes: 79 additions & 0 deletions cmd/go-runner/plugins/response_rewrite.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package plugins

import (
"encoding/json"
"net/http"

pkgHTTP "github.com/apache/apisix-go-plugin-runner/pkg/http"
"github.com/apache/apisix-go-plugin-runner/pkg/log"
"github.com/apache/apisix-go-plugin-runner/pkg/plugin"
)

func init() {
err := plugin.RegisterPlugin(&ResponseRewrite{})
if err != nil {
log.Fatalf("failed to register plugin response-rewrite: %s", err)
}
}

// ResponseRewrite is a demo to show how to rewrite response data.
type ResponseRewrite struct {
}

type ResponseRewriteConf struct {
Status int `json:"status"`
Headers map[string]string `json:"headers"`
Body string `json:"body"`
}

func (p *ResponseRewrite) Name() string {
return "response-rewrite"
}

func (p *ResponseRewrite) ParseConf(in []byte) (interface{}, error) {
conf := ResponseRewriteConf{}
err := json.Unmarshal(in, &conf)
return conf, err
}

func (p *ResponseRewrite) RequestFilter(interface{}, http.ResponseWriter, pkgHTTP.Request) {
}

func (p *ResponseRewrite) ResponseFilter(conf interface{}, w pkgHTTP.Response) {
cfg := conf.(ResponseRewriteConf)
if cfg.Status > 0 {
w.WriteHeader(200)
}

w.Header().Set("X-Resp-A6-Runner", "Go")
if len(cfg.Headers) > 0 {
for k, v := range cfg.Headers {
w.Header().Set(k, v)
}
}

if len(cfg.Body) == 0 {
return
}
_, err := w.Write([]byte(cfg.Body))
if err != nil {
log.Errorf("failed to write: %s", err)
}
}
73 changes: 73 additions & 0 deletions cmd/go-runner/plugins/response_rewrite_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package plugins

import (
"io/ioutil"
"testing"

pkgHTTPTest "github.com/apache/apisix-go-plugin-runner/pkg/httptest"

"github.com/stretchr/testify/assert"
)

func TestResponseRewrite(t *testing.T) {
in := []byte(`{"status":200, "headers":{"X-Server-Id":"9527"},"body":"response rewrite"}`)
rr := &ResponseRewrite{}
conf, err := rr.ParseConf(in)
assert.Nil(t, err)
assert.Equal(t, 200, conf.(ResponseRewriteConf).Status)
assert.Equal(t, "9527", conf.(ResponseRewriteConf).Headers["X-Server-Id"])
assert.Equal(t, "response rewrite", conf.(ResponseRewriteConf).Body)

w := pkgHTTPTest.NewRecorder()
w.Code = 502
w.HeaderMap.Set("X-Resp-A6-Runner", "Java")
rr.ResponseFilter(conf, w)

body, _ := ioutil.ReadAll(w.Body)
assert.Equal(t, 200, w.StatusCode())
assert.Equal(t, "Go", w.Header().Get("X-Resp-A6-Runner"))
assert.Equal(t, "9527", w.Header().Get("X-Server-Id"))
assert.Equal(t, "response rewrite", string(body))
}

func TestResponseRewrite_BadConf(t *testing.T) {
in := []byte(``)
rr := &ResponseRewrite{}
_, err := rr.ParseConf(in)
assert.NotNil(t, err)
}

func TestResponseRewrite_ConfEmpty(t *testing.T) {
in := []byte(`{}`)
rr := &ResponseRewrite{}
conf, err := rr.ParseConf(in)
assert.Nil(t, err)
assert.Equal(t, 0, conf.(ResponseRewriteConf).Status)
assert.Equal(t, 0, len(conf.(ResponseRewriteConf).Headers))
assert.Equal(t, "", conf.(ResponseRewriteConf).Body)

w := pkgHTTPTest.NewRecorder()
w.Code = 502
w.HeaderMap.Set("X-Resp-A6-Runner", "Java")
rr.ResponseFilter(conf, w)
assert.Equal(t, 502, w.StatusCode())
assert.Equal(t, "Go", w.Header().Get("X-Resp-A6-Runner"))
assert.Equal(t, "", conf.(ResponseRewriteConf).Body)
}
112 changes: 112 additions & 0 deletions pkg/httptest/recorder.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package httptest

import (
"bytes"
"net/http"

pkgHTTP "github.com/apache/apisix-go-plugin-runner/pkg/http"
)

// ResponseRecorder is an implementation of pkgHTTP.Response that
// records its mutations for later inspection in tests.
type ResponseRecorder struct {
// Code is the HTTP response code set at initialization.
Code int

// HeaderMap contains the headers explicitly set by the Handler.
// It is an internal detail.
HeaderMap pkgHTTP.Header

// body is the buffer to which the Handler's Write calls are sent.
// If nil, the Writes are silently discarded.
Body *bytes.Buffer

statusCode int
id uint32
}

// NewRecorder returns an initialized ResponseRecorder.
func NewRecorder() *ResponseRecorder {
return &ResponseRecorder{
HeaderMap: newHeader(),
Body: new(bytes.Buffer),
}
}

// ID is APISIX rpc's id.
func (rw *ResponseRecorder) ID() uint32 {
return rw.id
}

// StatusCode returns the response code.
//
// Note that if a Handler never calls WriteHeader,
// this will be initial status code, rather than the implicit
// http.StatusOK.
func (rw *ResponseRecorder) StatusCode() int {
if rw.statusCode == 0 {
return rw.Code
}

return rw.statusCode
}

// Header implements pkgHTTP.Response. It returns the response
// headers to mutate within a handler.
func (rw *ResponseRecorder) Header() pkgHTTP.Header {
m := rw.HeaderMap
if m == nil {
rw.HeaderMap = newHeader()
}
return m
}

// Write implements pkgHTTP.Response.
// The data in buf is written to rw.Body, if not nil.
func (rw *ResponseRecorder) Write(buf []byte) (int, error) {
if rw.Body == nil {
rw.Body = &bytes.Buffer{}
}
return rw.Body.Write(buf)
}

// WriteHeader implements pkgHTTP.Response.
// The statusCode is only allowed to be written once.
func (rw *ResponseRecorder) WriteHeader(code int) {
if rw.statusCode != 0 {
return
}

rw.statusCode = code
}

type Header struct {
http.Header
}

func (h *Header) View() http.Header {
return h.Header
}

func newHeader() *Header {
return &Header{
Header: http.Header{},
}
}
72 changes: 72 additions & 0 deletions tests/e2e/plugins/plugins_response_rewrite_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package plugins_test

import (
"net/http"

"github.com/apache/apisix-go-plugin-runner/tests/e2e/tools"
"github.com/gavv/httpexpect/v2"
"github.com/onsi/ginkgo"
"github.com/onsi/ginkgo/extensions/table"
)

var _ = ginkgo.Describe("ResponseRewrite Plugin", func() {
table.DescribeTable("tries to test ResponseRewrite feature.",
func(tc tools.HttpTestCase) {
tools.RunTestCase(tc)
},
table.Entry("Config APISIX.", tools.HttpTestCase{
Object: tools.GetA6Expect(),
Method: http.MethodPut,
Path: "/apisix/admin/routes/1",
Body: `{
"uri":"/test/go/runner/say",
"plugins":{
"ext-plugin-post-resp":{
"conf":[
{
"name":"response-rewrite",
"value":"{\"headers\":{\"X-Server-Id\":\"9527\"},\"body\":\"response rewrite\"}"
}
]
}
},
"upstream":{
"nodes":{
"web:8888":1
},
"type":"roundrobin"
}
}`,
Headers: map[string]string{"X-API-KEY": tools.GetAdminToken()},
ExpectStatusRange: httpexpect.Status2xx,
}),
table.Entry("Should rewrite response.", tools.HttpTestCase{
Object: tools.GetA6Expect(),
Method: http.MethodGet,
Path: "/test/go/runner/say",
ExpectBody: []string{"response rewrite"},
ExpectStatus: http.StatusOK,
ExpectHeaders: map[string]string{
"X-Resp-A6-Runner": "Go",
"X-Server-Id": "9527",
},
}),
)
})