1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
|
// Copyright 2017 PingCAP, Inc.
//
// Licensed 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 fn
import (
"context"
"encoding/json"
"net/http"
"reflect"
)
type (
// ErrorEncoder encode error to response body
ErrorEncoder func(ctx context.Context, err error) interface{}
// ResponseEncoder encode payload to response body
ResponseEncoder func(ctx context.Context, payload interface{}) interface{}
// fn represents a handler that contains a bundle of hooks
fn struct {
plugins []PluginFunc
adapter adapter
}
)
var (
errorEncoder ErrorEncoder
responseEncoder ResponseEncoder
)
func failure(ctx context.Context, w http.ResponseWriter, err error) {
statusCode := http.StatusBadRequest
if v, ok := UnwrapErrorStatusCode(err); ok {
statusCode = v
}
w.WriteHeader(statusCode)
_ = json.NewEncoder(w).Encode(errorEncoder(ctx, err))
}
func success(ctx context.Context, w http.ResponseWriter, data interface{}) {
if data == nil || (reflect.ValueOf(data).Kind() == reflect.Ptr && reflect.ValueOf(data).IsNil()) {
w.WriteHeader(http.StatusNoContent)
} else {
_ = json.NewEncoder(w).Encode(responseEncoder(ctx, data))
}
}
func (fn *fn) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
var (
ctx = r.Context()
err error
resp interface{}
)
for _, b := range globalPlugins {
ctx, err = b(ctx, r)
if err != nil {
failure(ctx, w, err)
return
}
}
for _, b := range fn.plugins {
ctx, err = b(ctx, r)
if err != nil {
failure(ctx, w, err)
return
}
}
resp, err = fn.adapter.invoke(ctx, w, r)
if err != nil {
failure(ctx, w, err)
return
}
success(ctx, w, resp)
}
func (fn *fn) Plugin(before ...PluginFunc) *fn {
for _, b := range before {
if b != nil {
fn.plugins = append(fn.plugins, b)
}
}
return fn
}
func init() {
errorEncoder = func(ctx context.Context, err error) interface{} {
return err.Error()
}
responseEncoder = func(ctx context.Context, payload interface{}) interface{} {
return payload
}
}
|