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 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
|
# fn
This library aims to simplify the construction of JSON API service,
`fn.Wrap` is able to wrap any function to adapt the interface of
`http.Handler`, which unmarshals POST data to a struct automatically.
## Benchmark
```
BenchmarkIsBuiltinType-8 50000000 33.5 ns/op 0 B/op 0 allocs/op
BenchmarkSimplePlainAdapter_Invoke-8 2000000 757 ns/op 195 B/op 3 allocs/op
BenchmarkSimpleUnaryAdapter_Invoke-8 2000000 681 ns/op 946 B/op 5 allocs/op
BenchmarkGenericAdapter_Invoke-8 2000000 708 ns/op 946 B/op 5 allocs/op
```
## Support types
```
io.ReadCloser // request.Body
http.Header // request.Header
fn.Form // request.Form
fn.PostForm // request.PostForm
*fn.Form // request.Form
*fn.PostForm // request.PostForm
*url.URL // request.URL
*multipart.Form // request.MultipartForm
*http.Request // raw request
```
## Usage
```go
http.Handle("/test", fn.Wrap(test))
func test(io.ReadCloser, http.Header, fn.Form, fn.PostForm, *CustomizedRequestType, *url.URL, *multipart.Form) (*CustomizedResponseType, error)
```
## Examples
### Basic
```go
package examples
import (
"io"
"mime/multipart"
"net/http"
"net/url"
"github.com/pingcap/fn"
)
type Request struct {
Username string `json:"username"`
Password string `json:"password"`
}
type Response struct {
Token string `json:"token"`
}
func api1() (*Response, error) {
return &Response{Token: "token"}, nil
}
func api2(request *Request) (*Response, error) {
token := request.Username + request.Password
return &Response{Token: token}, nil
}
func api3(rawreq *http.Request, request *Request) (*Response, error) {
token := request.Username + request.Password
return &Response{Token: token}, nil
}
func api4(rawreq http.Header, request *Request) (*Response, error) {
token := request.Username + request.Password
return &Response{Token: token}, nil
}
func api5(form *fn.Form, request *Request) (*Response, error) {
token := request.Username + request.Password + form.Get("type")
return &Response{Token: token}, nil
}
func api6(body io.ReadCloser, request *Request) (*Response, error) {
token := request.Username + request.Password
return &Response{Token: token}, nil
}
func api7(form *multipart.Form, request *Request) (*Response, error) {
token := request.Username + request.Password
return &Response{Token: token}, nil
}
func api7(urls *url.URL, request *Request) (*Response, error) {
token := request.Username + request.Password
return &Response{Token: token}, nil
}
func api8(urls *url.URL, form *multipart.Form, body io.ReadCloser, rawreq http.Header, request *Request) (*Response, error) {
token := request.Username + request.Password
return &Response{Token: token}, nil
}
```
### Plugins
```go
package examples
import (
"context"
"errors"
"io"
"log"
"mime/multipart"
"net/http"
"net/url"
"strings"
"github.com/pingcap/fn"
)
var PermissionDenied = errors.New("permission denied")
func logger(ctx context.Context, req *http.Request) (context.Context, error) {
log.Println("Request", req.RemoteAddr, req.URL.String())
return ctx, nil
}
func ipWhitelist(ctx context.Context, req *http.Request) (context.Context, error) {
if strings.HasPrefix(req.RemoteAddr, "172.168") {
return ctx, PermissionDenied
}
return ctx, nil
}
func auth(ctx context.Context, req *http.Request) (context.Context, error) {
token := req.Header.Get("X-Auth-token")
_ = token // Validate token (e.g: query db)
if token != "valid" {
return ctx, fn.ErrorWithStatusCode(PermissionDenied, http.StatusForbidden)
}
return ctx, nil
}
type Request struct {
Username string `json:"username"`
Password string `json:"password"`
}
type Response struct {
Token string `json:"token"`
}
func example() {
fn.Plugin(logger, ipWhitelist, auth)
http.Handle("/api1", fn.Wrap(api1))
http.Handle("/api2", fn.Wrap(api2))
}
// api1 and api2 request have be validated by `ipWhitelist` and `auth`
func api1() (*Response, error) {
return &Response{Token: "token"}, nil
}
func api2(request *Request) (*Response, error) {
token := request.Username + request.Password
return &Response{Token: token}, nil
}
```
### `fn.Group`
```go
package examples
import (
"context"
"errors"
"io"
"log"
"mime/multipart"
"net/http"
"net/url"
"strings"
"github.com/pingcap/fn"
)
var PermissionDenied = errors.New("permission denied")
func logger(ctx context.Context, req *http.Request) (context.Context, error) {
log.Println("Request", req.RemoteAddr, req.URL.String())
return ctx, nil
}
func ipWhitelist(ctx context.Context, req *http.Request) (context.Context, error) {
if strings.HasPrefix(req.RemoteAddr, "172.168") {
return ctx, PermissionDenied
}
return ctx, nil
}
func auth(ctx context.Context, req *http.Request) (context.Context, error) {
token := req.Header.Get("X-Auth-token")
_ = token // Validate token (e.g: query db)
if token != "valid" {
return ctx, fn.ErrorWithStatusCode(PermissionDenied, http.StatusForbidden)
}
return ctx, nil
}
type User struct {
Balance int64
}
func queryUserFromRedis(ctx context.Context, req *http.Request) (context.Context, error) {
token := req.Header.Get("X-Auth-token")
_ = token // Validate token (e.g: query db)
if token != "valid" {
return ctx, fn.ErrorWithStatusCode(PermissionDenied, http.StatusForbidden)
}
user := &User{
Balance: 10000, // balance from redis
}
return context.WithValue(ctx, "user", user), nil
}
type Response struct {
Balance int64 `json:"balance"`
}
func example() {
// Global plugins
fn.Plugin(logger, ipWhitelist, auth)
group := fn.NewGroup()
// Group plugins
group.Plugin(queryUserFromRedis)
http.Handle("/user/balance", group.Wrap(fetchBalance))
http.Handle("/user/buy", group.Wrap(buy))
}
func fetchBalance(ctx context.Context) (*Response, error) {
user := ctx.Value("user").(*User)
return &Response{Balance: user.Balance}, nil
}
func buy(ctx context.Context) (*Response, error) {
user := ctx.Value("user").(*User)
if user.Balance < 100 {
return nil, errors.New("please check balance")
}
user.Balance -= 100
return &Response{Balance: user.Balance}, nil
}
```
### ResponseEncoder
```go
package examples
import (
"context"
"errors"
"io"
"log"
"mime/multipart"
"net/http"
"net/url"
"strings"
"github.com/pingcap/fn"
)
var PermissionDenied = errors.New("permission denied")
func logger(ctx context.Context, req *http.Request) (context.Context, error) {
log.Println("Request", req.RemoteAddr, req.URL.String())
return ctx, nil
}
func ipWhitelist(ctx context.Context, req *http.Request) (context.Context, error) {
if strings.HasPrefix(req.RemoteAddr, "172.168") {
return ctx, PermissionDenied
}
return ctx, nil
}
func auth(ctx context.Context, req *http.Request) (context.Context, error) {
token := req.Header.Get("X-Auth-token")
_ = token // Validate token (e.g: query db)
if token != "valid" {
return ctx, fn.ErrorWithStatusCode(PermissionDenied, http.StatusForbidden)
}
return ctx, nil
}
func injectRequest(ctx context.Context, req *http.Request) (context.Context, error) {
return context.WithValue(ctx, "_rawreq", req), nil
}
type User struct {
Balance int64
}
func queryUserFromRedis(ctx context.Context, req *http.Request) (context.Context, error) {
token := req.Header.Get("X-Auth-token")
_ = token // Validate token (e.g: query db)
if token != "valid" {
return ctx, fn.ErrorWithStatusCode(PermissionDenied, http.StatusForbidden)
}
user := &User{
Balance: 10000, // balance from redis
}
return context.WithValue(ctx, "user", user), nil
}
type Response struct {
Balance int64 `json:"balance"`
}
type ResponseMessage struct {
Code int `json:"code"`
Data interface{} `json:"data"`
}
type ErrorMessage struct {
Code int `json:"code"`
Error string `json:"error"`
}
func example() {
// Global plugins
fn.Plugin(logger, ipWhitelist, auth, injectRequest)
// Uniform all responses
fn.SetErrorEncoder(func(ctx context.Context, err error) interface{} {
req := ctx.Value("_rawreq").(*http.Request)
log.Println("Error occurred: ", req.URL, err)
return &ErrorMessage{
Code: -1,
Error: err.Error(),
}
})
fn.SetResponseEncoder(func(ctx context.Context, payload interface{}) interface{} {
return &ResponseMessage{
Code: 1,
Data: payload,
}
})
group := fn.NewGroup()
// Group plugins
group.Plugin(queryUserFromRedis)
http.Handle("/user/balance", group.Wrap(fetchBalance))
http.Handle("/user/buy", group.Wrap(buy))
}
func fetchBalance(ctx context.Context) (*Response, error) {
user := ctx.Value("user").(*User)
return &Response{Balance: user.Balance}, nil
}
func buy(ctx context.Context) (*Response, error) {
user := ctx.Value("user").(*User)
if user.Balance < 100 {
return nil, errors.New("please check balance")
}
user.Balance -= 100
return &Response{Balance: user.Balance}, nil
}
```
|