request sdk 封裝

kenuo發表於2019-07-09
package http

import (
    "fmt"

    "github.com/imroc/req"
    logger "xxx" //logger日誌封裝
    util "xxxx/sdk-utils"
)

type method string

const (
    GET    method = "GET"
    POST   method = "POST"
    PUT    method = "PUT"
    PATCH  method = "PATCH"
    DELETE method = "DELETE"
)

type Response struct {
    Data []byte
}

//反序列化操作
func (r *Response) Deserialize(object interface{}) (err error) {
    err = util.JSONUnmarshal(r.Data, object)
    return err
}

//支援所有型別請求.
func Request(method method, url string, v ...interface{}) (response *Response, err error) {
    var r *req.Resp
    response = new(Response)
    switch method {
    case "GET":
        r, err = req.Get(url, v...)
    case "POST":
        r, err = req.Post(url, v...)
    case "PUT":
        r, err = req.Put(url, v...)
    case "PATCH":
        r, err = req.Patch(url, v...)
    case "DELETE":
        r, err = req.Delete(url, v...)
    }

    if err != nil {
        return
    }

    statusCode := r.Response().StatusCode
    if statusCode != 200 {
        err = fmt.Errorf("http cilent code err: %d", statusCode)
        return
    }

    response.Data = r.Bytes()
    return
}

by JeffreyBool blog :point_right: link

相關文章