如何使这段Go代码更干练?

如何使这段Go代码更干练?,go,dry,Go,Dry,我正在为RESTAPI实现一个Go包装器。它基本上解析JSON,并应返回适当的结构类型。我发现自己做了很多这样的事情: // GetBlueprintDetails returns details about a blueprint func (c *Client) GetBlueprintDetails(projectID string, blueprintID string) (*BlueprintDetails, *APIError) { path := fmt.Sprintf("

我正在为RESTAPI实现一个Go包装器。它基本上解析JSON,并应返回适当的结构类型。我发现自己做了很多这样的事情:

// GetBlueprintDetails returns details about a blueprint
func (c *Client) GetBlueprintDetails(projectID string, blueprintID string) (*BlueprintDetails, *APIError) {
    path := fmt.Sprintf("projects/%s/blueprints/%s", projectID, blueprintID)
    res, err := c.Request("GET", path, nil, nil)
    if err != nil {
        return nil, err
    }
    var ret BlueprintDetails
    e := json.Unmarshal(res.Body, &ret)
    if e != nil {
        return nil, &APIError{Error: &e}
    }
    return &ret, nil
}

// GetProjects returns a list of projects for the user
func (c *Client) GetProjects() (*[]Project, *APIError) {
    res, err := c.Request("GET", "projects", nil, nil)
    if err != nil {
        return nil, err
    }
    var ret []Project
    e := json.Unmarshal(res.Body, &ret)
    if e != nil {
        return nil, &APIError{Error: &e}
    }
    return &ret, nil
}
这两个函数之间的唯一区别是解封结构的类型。我知道围棋中没有通用的,但必须有一个模式使它更干燥


有什么想法吗?

您可以创建一个
MakeRequest
函数,该函数执行http请求部分并将json解组到结构

下面是如何操作的,请看一下
MakeRequest
函数

// GetBlueprintDetails returns details about a blueprint
func (c *Client) GetBlueprintDetails(projectID string, blueprintID string) (*BlueprintDetails, *APIError) {
    path := fmt.Sprintf("projects/%s/blueprints/%s", projectID, blueprintID)
    bluePrintDetails = new(BlueprintDetails)
    err := c.MakeRequest("GET", path, bluePrintDetails)
    return bluePrintDetails, err
}

// GetProjects returns a list of projects for the user
func (c *Client) GetProjects() (*[]Project, *APIError) {
    projects = make([]Project, 0)
    err := c.MakeRequest("GET", "project", &projects)
    return &projects, err
}

func (c *Client) MakeRequest(method string, path string, response interface{}) *APIError {
    res, err := c.Request(method, path, nil, nil)
    if err != nil {
        return nil, err
    }
    e := json.Unmarshal(res.Body, response)
    if e != nil {
        return &APIError{Error: &e}
    }
    return nil
}

我遇到过类似的问题,创建一个fat结构来解析这两种类型的请求,其他变量是否为空?你能分享“BlueprintDetails”结构吗?@Sarathsp你能解释一下为什么
((c*客户端))
没有使用
(c*客户端)
?@GujaratSantana哦,那是个打字错误。谢谢你指出这一点