From 95411aff776c2f7fc492899ea16ce90882d0dd8d Mon Sep 17 00:00:00 2001 From: John Date: Thu, 6 Feb 2020 11:14:38 +0800 Subject: [PATCH] improve ghttp.Request for making the request body reusable for multiple times --- .example/net/ghttp/server/body.go | 22 ++++++++++++++++++++ net/ghttp/ghttp_request_body.go | 34 +++++++++++++++++++++++++++++++ net/ghttp/ghttp_request_param.go | 1 + 3 files changed, 57 insertions(+) create mode 100644 .example/net/ghttp/server/body.go create mode 100644 net/ghttp/ghttp_request_body.go diff --git a/.example/net/ghttp/server/body.go b/.example/net/ghttp/server/body.go new file mode 100644 index 000000000..cb31dc20d --- /dev/null +++ b/.example/net/ghttp/server/body.go @@ -0,0 +1,22 @@ +package main + +import ( + "fmt" + "github.com/gogf/gf/frame/g" + "github.com/gogf/gf/net/ghttp" + "io/ioutil" +) + +func main() { + s := g.Server() + s.SetIndexFolder(true) + s.BindHandler("/", func(r *ghttp.Request) { + body1 := r.GetBody() + body2, _ := ioutil.ReadAll(r.Body) + fmt.Println(body1) + fmt.Println(body2) + r.Response.Write("hello world") + }) + s.SetPort(8999) + s.Run() +} diff --git a/net/ghttp/ghttp_request_body.go b/net/ghttp/ghttp_request_body.go new file mode 100644 index 000000000..69729ccf2 --- /dev/null +++ b/net/ghttp/ghttp_request_body.go @@ -0,0 +1,34 @@ +// Copyright 2018 gf Author(https://github.com/gogf/gf). All Rights Reserved. +// +// This Source Code Form is subject to the terms of the MIT License. +// If a copy of the MIT was not distributed with this file, +// You can obtain one at https://github.com/gogf/gf. + +package ghttp + +import ( + "bytes" + "io/ioutil" +) + +// bodyReadCloser implements the io.ReadCloser interface +// which is used for reading request body content multiple times. +type BodyReadCloser struct { + *bytes.Buffer +} + +// RefillBody refills the request body object after read all of its content. +// It makes the request body reusable for next reading. +func (r *Request) RefillBody() { + if r.bodyContent == nil { + r.bodyContent, _ = ioutil.ReadAll(r.Body) + } + r.Body = &BodyReadCloser{ + bytes.NewBuffer(r.bodyContent), + } +} + +// Close implements the io.ReadCloser interface. +func (b *BodyReadCloser) Close() error { + return nil +} diff --git a/net/ghttp/ghttp_request_param.go b/net/ghttp/ghttp_request_param.go index 087f11558..8b5698350 100644 --- a/net/ghttp/ghttp_request_param.go +++ b/net/ghttp/ghttp_request_param.go @@ -71,6 +71,7 @@ func (r *Request) GetRawString() string { func (r *Request) GetBody() []byte { if r.bodyContent == nil { r.bodyContent, _ = ioutil.ReadAll(r.Body) + r.RefillBody() } return r.bodyContent }