Documentation ¶
Index ¶
- func BindRequest(ptr interface{}, r *http.Request) error
- func DefaultRequestRetryCheck(resp *http.Response, err error) (shouldRetry bool)
- func DumpRequestResponse(req *http.Request, resp *http.Response, body bool) (data []byte)
- func DumpRequestResponseString(req *http.Request, resp *http.Response, body bool) (data string)
- func GracefulClose(closeFunc func())
- func MockMatchCount(c *Context, counts map[string]string) (key string)
- func MockMatchSceneCount(c *Context, routers map[string]map[string]string) (replyKey string)
- type Client
- func (client *Client) CloseIdleConnections()
- func (client *Client) Do(request *http.Request) (resp *http.Response, bodyClose func() error, statusCode int, err error)deprecated
- func (c *Client) Req(ctx context.Context, method Method, u string, req Req) (result HttpResult, err error)
- func (client *Client) Send(ctx context.Context, method Method, origin string, path string, ...) (httpResult HttpResult, bodyClose func() error, statusCode int, err error)deprecated
- type Context
- func (c *Context) AbsURL() (url string)
- func (c *Context) BindRequest(ptr interface{}) error
- func (c *Context) CheckError(err error)
- func (c *Context) CheckPanic(r interface{})
- func (c *Context) ClearCookie(cookie *http.Cookie)
- func (c *Context) Cookie(name string) (value *http.Cookie, has bool, err error)
- func (c *Context) Host() (host string)
- func (c *Context) Param(name string) (param string, err error)
- func (c *Context) RealIP() (ip string)
- func (c *Context) Redirect(url string, code int) (err error)
- func (c *Context) Render(render func(buffer *bytes.Buffer) error) error
- func (c *Context) Scheme() (scheme string)
- func (c *Context) SetCookie(cookie *http.Cookie)
- func (c *Context) UnmarshalJSONFromQuery(queryKey string, ptr interface{}) (err error)
- func (c *Context) WriteBytes(b []byte) error
- func (c *Context) WriteJSON(v interface{}) error
- func (c *Context) WriteStatusCode(statusCode int)
- type ExampleReplyPost
- type ExampleSendQuery
- type Group
- func (group *Group) Handle(path string, handler http.Handler)
- func (group *Group) HandleFunc(route Route, handler HandleFunc)
- func (group *Group) NetHttpHandleFunc(path string, handler func(w http.ResponseWriter, r *http.Request))
- func (group *Group) Use(middleware func(c *Context, next Next) (err error))
- type HandleFunc
- type Helper
- type HttpResult
- func (v HttpResult) Dump(body ...bool) (dump string)
- func (v HttpResult) DumpBytes(body ...bool) (data []byte)
- func (v HttpResult) Elapsed() time.Duration
- func (v HttpResult) GetBody() (body []byte, err error)
- func (v HttpResult) ReadBody(unmarshal func(data []byte, v interface{}) error, ptr interface{}) (err error)
- func (v HttpResult) String() (dump string)
- type Method
- type Mock
- type MockRender
- type MockReply
- type MockRequest
- type MockServer
- type MockServerOption
- type Next
- type Req
- type RequestMarshaler
- type RequestRetry
- type RequestUnmarshaler
- type Response
- type Route
- type Router
- func (router *Router) FileServer(prefix string, dir string, noCache bool, ...)
- func (serve *Router) Group() *Group
- func (serve *Router) Handle(path string, handler http.Handler)
- func (serve *Router) HandleFunc(route Route, handler HandleFunc)
- func (router Router) LogPatterns(server *http.Server)
- func (serve *Router) NetHttpHandleFunc(path string, handler func(w http.ResponseWriter, r *http.Request))
- func (router Router) PrefixHandler(prefix string, handler http.Handler)
- func (router Router) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (serve *Router) Use(middleware func(c *Context, next Next) (err error))
- type RouterOption
- type SendRequest
- type Test
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func BindRequest ¶
func DumpRequestResponse ¶
func GracefulClose ¶
func GracefulClose(closeFunc func())
Types ¶
type Client ¶
func (*Client) CloseIdleConnections ¶
func (client *Client) CloseIdleConnections()
func (*Client) Do
deprecated
func (client *Client) Do(request *http.Request) (resp *http.Response, bodyClose func() error, statusCode int, err error)
Deprecated: Use client.Req Do 消费 http.Response{}.Body 后必须 Close xhttp.Client{}.Do() 的出参提供了一个安全的 bodyClose bodyClose 会在 resp 为 nil 时 不调用 resp.Body.Close 以防止 空指针错误 请求发起成功时候应该判断 响应的 statusCode,而不是忽视 statusCode xhttp.Client{}.Do() 的出参提供了一个等同于 resp.StatusCode 的 statusCode 参数 用于提醒开发人员每次调用完 Do 之后需要根据不同的状态码进行相应的处理措施 xhttp.Client{}.Do() 的实现非常简单,有兴趣的可以直接查看源码帮助理解
Example ¶
net/http 的 &http.Client{}.Do() 函数只返回了 resp, err 实际上我们一定要记得 resp.Body.Close() ,但是 resp 可能是个 nil ,此时 运行 resp.Body.Close() 会出现空指针错误 并且一般情况应该判断 resp.StatusCode != 200 并返回错误 所以 &xhttp.Client{}.Do() 的函数签名是 (client *Client) Do(request *http.Request) (resp *http.Response, bodyClose func() error, statusCode int, err error) 这样使用者就不容易忘记处理 statusCode 和 bodyClose ,并且 bodyClose 处理了resp 空 nil的情况
package main import ( "context" xerr "github.com/goclub/error" xhttp "github.com/goclub/http" xjson "github.com/goclub/json" "log" "net/http" ) func main() { log.Print("ExampleClient_Do") ctx := context.TODO() client := xhttp.NewClient(&http.Client{}) url := "https://httpbin.org/json" request, err := http.NewRequestWithContext(ctx, "GET", url, nil) if err != nil { panic(err) } resp, bodyClose, statusCode, err := client.Do(request) if err != nil { panic(err) } defer bodyClose() if statusCode != 200 { panic(xerr.New("response " + resp.Status)) } var reply xhttp.ExampleReplyPost err = xjson.NewDecoder(resp.Body).Decode(&reply) if err != nil { panic(err) } log.Printf("response %+v", reply) // [{ID:6 Title:OVMVHWVHfA Views:20 Published:false CreatedAt:1936-09-10T20:19:28Z} {ID:57 Title:jOyYTxTfVV Views:20 Published:false CreatedAt:1942-04-18T13:44:54Z} {ID:82 Title:CdnSvYuNzs Views:20 Published:true CreatedAt:1907-05-01T23:53:45Z} {ID:97 Title:CWjFddEmda Views:20 Published:true CreatedAt:1971-01-13T08:22:23Z}] }
Output:
func (*Client) Send
deprecated
func (client *Client) Send(ctx context.Context, method Method, origin string, path string, request SendRequest) (httpResult HttpResult, bodyClose func() error, statusCode int, err error)
Deprecated: Use client.Req Send 发送 query from json 等常见请求
Example ¶
package main import ( "context" xerr "github.com/goclub/error" xhttp "github.com/goclub/http" xjson "github.com/goclub/json" "log" "net/http" ) func main() { { log.Print("ExampleClient_Send:query") ctx := context.TODO() client := xhttp.NewClient(&http.Client{}) err := func() (err error) { httpResult, bodyClose, statusCode, err := client.Send(ctx, xhttp.GET, "https://httpbin.org", "/json", xhttp.SendRequest{ Query: xhttp.ExampleSendQuery{ Published: true, Limit: 2, }, JSON: map[string]interface{}{"name": "goclub"}, }) // 1. 遇到错误向上传递 if err != nil { return } // 2. bodyClose 防止内存泄露 defer bodyClose() // 3. 检查状态码 if statusCode != 200 { // 状态码错误时候记录日志 log.Print(httpResult.Dump(true)) err = xerr.New("http response statusCode != 200") return } // json解码 var reply xhttp.ExampleReplyPost err = httpResult.ReadBody(xjson.Unmarshal, &reply) if err != nil { // 解码错误时记录日志 log.Print(httpResult.Dump(true)) return } // 响应 log.Print("reply", reply) return }() xerr.PrintStack(err) } }
Output:
type Context ¶
type Context struct { Writer http.ResponseWriter Request *http.Request // contains filtered or unexported fields }
Context 包含 *http.Request http.ResponseWriter 并封装一些便捷方法
func NewContext ¶
func (*Context) AbsURL ¶
AbsURL return "http://domain.com/path?q=1"
func (*Context) BindRequest ¶
BindRequest - 绑定请求,支持自定义结构体标签 `query` `form` `param`
func (*Context) CheckError ¶
CheckError 让 Router{}.OnCatchError 处理传入的错误
func (*Context) CheckPanic ¶
func (c *Context) CheckPanic(r interface{})
CheckPanic 让 Router{}.OnCatchError 处理传入的错误
func (*Context) ClearCookie ¶
func (*Context) Param ¶
Param - 获取路由参数 比如路由是 xhttp.Route{xhttp.GET, "/user/{userID}"} 当请求 "/user/11" 时候通过 c.Param("userID") 可以获取到 "11"
func (*Context) UnmarshalJSONFromQuery ¶
UnmarshalJSONFromQuery 从 query 中读取json并解析
func (*Context) WriteBytes ¶
WriteBytes 等同于 writer.Write(data) ,但函数签名返回 error 不返回 int
func (*Context) WriteStatusCode ¶
type ExampleReplyPost ¶
type ExampleSendQuery ¶
func (ExampleSendQuery) Query ¶
func (r ExampleSendQuery) Query() (string, error)
通过实现结构体 Query() (string, error) 方法后传入 xhttp.SendRequest{}.Query 即可设置请求 query 参数
type Group ¶
type Group struct {
// contains filtered or unexported fields
}
func (*Group) HandleFunc ¶
func (group *Group) HandleFunc(route Route, handler HandleFunc)
func (*Group) NetHttpHandleFunc ¶
type HandleFunc ¶
type HttpResult ¶
type HttpResult struct { Request *http.Request Response *http.Response // contains filtered or unexported fields }
func (HttpResult) Dump ¶
func (v HttpResult) Dump(body ...bool) (dump string)
func (HttpResult) DumpBytes ¶
func (v HttpResult) DumpBytes(body ...bool) (data []byte)
func (HttpResult) Elapsed ¶
func (v HttpResult) Elapsed() time.Duration
func (HttpResult) GetBody ¶
func (v HttpResult) GetBody() (body []byte, err error)
func (HttpResult) ReadBody ¶
func (v HttpResult) ReadBody(unmarshal func(data []byte, v interface{}) error, ptr interface{}) (err error)
func (HttpResult) String ¶
func (v HttpResult) String() (dump string)
type Method ¶
type Method string
const CONNECT Method = "CONNECT"
const DELETE Method = "DELETE"
const GET Method = "GET"
const HEAD Method = "HEAD"
const OPTIONS Method = "OPTIONS"
const PATCH Method = "PATCH"
const POST Method = "POST"
const PUT Method = "PUT"
const TRACE Method = "TRACE"
type Mock ¶
type Mock struct { Route Route `note:"路由"` Request MockRequest `note:"请求"` DisableDefaultReply string `note:"指定禁用默认响应的key"` Reply MockReply `note:"响应"` Match func(c *Context) (replyKey string) `note:"根据请求参数决定响应结果"` MaxAutoCount int64 `note:"最大计数,默认5"` HandleFunc func(c *Context, replyKey string, data interface{}) (err error) Render string }
type MockRender ¶
type MockRender interface {
Render(templatePath string, data interface{}, w http.ResponseWriter) error
}
type MockRequest ¶
type MockRequest map[string]interface{}
type MockServer ¶
type MockServer struct {
// contains filtered or unexported fields
}
func NewMockServer ¶
func NewMockServer(option MockServerOption) MockServer
func (MockServer) Listen ¶
func (server MockServer) Listen(port int)
func (MockServer) PrefixHandle ¶
func (server MockServer) PrefixHandle(prefix string, handler http.Handler)
func (MockServer) URL ¶
func (ms MockServer) URL(mock Mock)
type MockServerOption ¶
type MockServerOption struct { DefaultReply map[string]interface{} OnlineMock string Render MockRender }
type Req ¶
type Req struct { QueryEncode func(q url.Values) (encode string) FormUrlencoded func(f url.Values) (encode string) FormData func(w *multipart.Writer) (err error) Header func(h http.Header) http.Header JSON interface{} Body io.Reader Debug bool Before func(r *http.Request) (err error) NotCheckStatusCode bool Defer func(result HttpResult, err error) }
type RequestMarshaler ¶
type RequestRetry ¶
type RequestUnmarshaler ¶
type Router ¶
type Router struct { OnCatchError func(c *Context, err error) error OnCatchPanic func(c *Context, recoverValue interface{}) error // contains filtered or unexported fields }
func NewRouter ¶
func NewRouter(opt RouterOption) *Router
func (*Router) FileServer ¶
func (router *Router) FileServer(prefix string, dir string, noCache bool, middleware func(c *Context, next Next) (err error))
example: dir := path.Join(os.Getenv("GOPATH"), "src/github.com/goclub/http/example/internal/gin/public") defer r.FileServer("/public", dir, true) noCache 不使用缓存
func (*Router) HandleFunc ¶
func (serve *Router) HandleFunc(route Route, handler HandleFunc)
func (Router) LogPatterns ¶
func (*Router) NetHttpHandleFunc ¶
func (Router) PrefixHandler ¶
type RouterOption ¶
type RouterOption struct { OnCatchError func(c *Context, err error) error OnCatchPanic func(c *Context, recoverValue interface{}) error // Configurable Handler to be used when no route matches. NotFoundHandler http.Handler // Configurable Handler to be used when the request method does not match the route. MethodNotAllowedHandler http.Handler }
type SendRequest ¶
type SendRequest struct { Query interface { Query() (string, error) } FormUrlencoded interface { FormUrlencoded() (string, error) } FormData interface { FormData(w *multipart.Writer) (err error) } Header interface { Header() (http.Header, error) } JSON interface{} Body io.Reader Debug bool Retry RequestRetry BeforeSend func(r *http.Request) (err error) // DoNotReturnRequestBody 控制返回的 httpResult.Request{}.Body 是否为空 // 在请求 Body 大时可以设置为 true 以提高性能 DoNotReturnRequestBody bool }
func (SendRequest) HttpRequest ¶
type Test ¶
type Test struct {
// contains filtered or unexported fields
}