-1

以下代码有错误:

错误:

controllers/controllers.go:80:53: 不能在 services.GetCharactersID 的参数中使用 c.Param(id) (type string) 作为 int 类型 controllers/controllers.go:80:54: undefined: id)

func GetCharactersID (c *gin.Context) {
    characters, err := services.GetCharactersID(c.Param("id"))
    if err!=nil {
        response:= domain.Response{Mensaje:err.Error()}
        c.JSON(http.StatusInternalServerError,response)
        return
    }
    c.JSON (http.StatusOK,characters)
}
//Services

func GetCharactersID (id int) (domain.Characters,error) {
    var err error
    characterss,err := GetCharactersID(id)
    s := strconv.Itoa(id)
    ts := "my_hashjavi"
    hash := GetHashString(ts+private_key+public_key)
    var url string = "https://gateway.marvel.com:443/v1/public"
    url += "/characters" + "/"
    url+= s + "?"
    url += "ts="+ts
    url += "&apikey="+ public_key
    url += "&hash="+ hash
    resp,err1 := http.Get(url)
    Data, err2 := ioutil.ReadAll(resp.Body)

    if err1 != nil || err2 != nil {
        err= errors.New("Error al obtener los personajes")
        return characterss,err
    }
    json.Unmarshal(Data,&characterss)
    return characterss , nil

}
4

1 回答 1

0

我没有你的完整代码,但我重构它并应用你关于 id is not a int 的修复

func GetCharactersID(c *gin.Context) {
    characters, err := services.GetCharactersID(c.Param("id"))
    if err != nil {
        response := domain.Response{Mensaje: err.Error()}
        c.JSON(http.StatusInternalServerError, response)
        return
    }
    c.JSON(http.StatusOK, characters)
}

func GetCharactersID(sID string) (domain.Characters, error) {
    base := "https://gateway.marvel.com:443/v1/public"
    ts := "my_hashjavi"
    id, err := strconv.Atoi(sID)
    if err != nil {
        return characterss, errors.New("xxx...")
    }

    characterss, err := GetCharactersID(sID)
    if err != nil {
        return characterss, errors.New("xxx...")
    }

    hash := GetHashString(ts + private_key + public_key)
    url := fmt.Sprint("%s/characters/%d?ts=%s&apikey=%s&hash=%s",
        base, sID, ts, public_key, hash)

    resp, err := http.Get(url)
    if err != nil
        return characterss, errors.New("xxx...")
    }

    data, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        return characterss, errors.New("xxx...")
    }

    err = json.Unmarshal(data, &characterss)
    if err != nil {
        return characterss, err
    }

    return characterss, errors.New("xxx...")
}
于 2020-02-14T17:03:19.253 回答