Table of Contents
问题内容
解决方法
Home Backend Development Golang How to properly use the AnonFiles API to publish files?

How to properly use the AnonFiles API to publish files?

Feb 09, 2024 am 09:12 AM
overflow

如何正确使用AnonFiles API发布文件?

php小编苹果为您带来关于如何正确使用AnonFiles API发布文件的指南。AnonFiles API是一个强大的工具,可以帮助您快速、安全地上传和分享文件。本指南将为您提供详细的步骤和示例,帮助您轻松掌握API的使用方法。无论您是开发者还是普通用户,都能从本指南中获得实用的技巧和建议,让您的文件分享体验更加顺畅和高效。让我们一起来探索AnonFiles API的魅力吧!

问题内容

我正在尝试创建一个函数,使用 anonfiles api 在 anonfiles.com 网站上托管您的文件。即使我正确使用了 api,它总是返回 nil。 响应缺少消息

func host(file string) {
    fileBytes, err := ioutil.ReadFile(file)
    if err != nil {
        fmt.Println("\033[1;31mCommand > Host: Could not read file,", err, "\033[0m")
        return
    }

    url := "https://api.anonfiles.com/upload"

    request, err := http.NewRequest("POST", url, bytes.NewBuffer(fileBytes))
    if err != nil {
        fmt.Println("\033[1;31mCommand > Host: Could not post request,", err, "\033[0m")
        return
    }

    request.Header.Set("Content-Type", "application/octet-stream")

    client := &http.Client{}
    response, err := client.Do(request)
    if err != nil {
        fmt.Println("\033[1;31mCommand > Host: Could not send request,", err, "\033[0m")
        return
    }
    defer response.Body.Close()

    body, err := ioutil.ReadAll(response.Body)
    if err != nil {
        fmt.Println("\033[1;31mCommand > Host: Could not read response,", err, "\033[0m")
        return
    }

    var result map[string]interface{}
    err = json.Unmarshal(body, &result)
    if err != nil {
        fmt.Println("\033[1;31mCommand > Host: Could not parse response,", err, "\033[0m")
        return
    }

    if response.StatusCode == 200 {
        if result["url"] == nil {
            fmt.Println("\033[1;31mCommand > Host: Response is missing URL\033[0m")
            return
        }
        fmt.Println("File hosted successfully:", result["url"].(string))
    } else {
        if result["message"] == nil {
            fmt.Println("\033[1;31mCommand > Host: Response is missing message\033[0m")
            return
        }
        fmt.Println("\033[1;31mCommand > Host:\033[0m", result["message"].(string))
    }
}
Copy after login

解决方法

我想花点时间将这些评论扩展为答案。

首先,正如我们已经讨论过的,您没有使用正确的 api 来上传文件。如果我们修改您的代码以显示完整的响应正文,如下所示:

client := &http.client{}
response, err := client.do(request)
if err != nil {
  fmt.println("\033[1;31mcommand > host: could not send request,", err, "\033[0m")
  return
}
defer response.body.close()

body, err := ioutil.readall(response.body)
if err != nil {
  fmt.println("\033[1;31mcommand > host: could not read response,", err, "\033[0m")
  return
}

fmt.printf("body:\n%s\n", body)
Copy after login

我们看到以下内容:

{
  "status": false,
  "error": {
    "message": "no file chosen.",
    "type": "error_file_not_provided",
    "code": 10
  }
}
Copy after login
Copy after login

我们收到此错误是因为您没有在 multipart/form-data 请求中提供 file 参数。 我之前链接到的帖子有几个示例发送多部分请求;我已经测试了其中的几个,它们似乎按预期工作。

您还对 api 返回的响应做出了错误的假设。如果我们使用 curl 发出成功的请求并捕获响应 json,我们会发现它如下所示:

{
  "status": true,
  "data": {
    "file": {
      "url": {
        "full": "https://anonfiles.com/k8cdobwey7/test_txt",
        "short": "https://anonfiles.com/k8cdobwey7"
      },
      "metadata": {
        "id": "k8cdobwey7",
        "name": "test.txt",
        "size": {
          "bytes": 12,
          "readable": "12 b"
        }
      }
    }
  }
}
Copy after login

请注意,没有 response["url"]response["message"]。如果您想要上传文件的url,则需要获取response["data"]["file"]["url"]["full"](或["short"])。

同样,我们可以看到上面的错误响应示例,如下所示:

{
  "status": false,
  "error": {
    "message": "no file chosen.",
    "type": "error_file_not_provided",
    "code": 10
  }
}
Copy after login
Copy after login

这不是 result["message"];那是 result["error"]["message"]

因为您要解组到 map[string] 接口 ,所以获取这些嵌套键会有点痛苦。我发现为上述响应创建 go 结构是最简单的,只需将其解组为适当类型的变量即可。

这让我得到以下类型:

type (
  anonfilesurl struct {
    full  string `json:"full"`
    short string `json:"short"`
  }

  anonfilesmetadata struct {
    id   string `json:"id"`
    name string `json:"name"`
    size struct {
      bytes    int    `json:"bytes"`
      readable string `json:"readable"`
    } `json:"size"`
  }

  anonfilesdata struct {
    file struct {
      url      anonfilesurl      `json:"url"`
      metadata anonfilesmetadata `json:"metadata"`
    } `json:"file"`
  }

  anonfileserror struct {
    message string
    type    string
    code    int
  }

  anonfilesresponse struct {
    status bool           `json:"status"`
    data   anonfilesdata  `json:"data"`
    error  anonfileserror `json:"error"`
  }
)
Copy after login

然后解组响应如下所示:

var result anonfilesresponse
err = json.unmarshal(body, &result)
Copy after login

我们可以请求以下字段:

fmt.Printf("URL: %s\n", result.Data.File.URL.Full)
Copy after login

The above is the detailed content of How to properly use the AnonFiles API to publish files?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1665
14
PHP Tutorial
1270
29
C# Tutorial
1250
24
Is H5 page production a front-end development? Is H5 page production a front-end development? Apr 05, 2025 pm 11:42 PM

Yes, H5 page production is an important implementation method for front-end development, involving core technologies such as HTML, CSS and JavaScript. Developers build dynamic and powerful H5 pages by cleverly combining these technologies, such as using the <canvas> tag to draw graphics or using JavaScript to control interaction behavior.

How to control the top and end of pages in browser printing settings through JavaScript or CSS? How to control the top and end of pages in browser printing settings through JavaScript or CSS? Apr 05, 2025 pm 10:39 PM

How to use JavaScript or CSS to control the top and end of the page in the browser's printing settings. In the browser's printing settings, there is an option to control whether the display is...

Why are the inline-block elements misaligned? How to solve this problem? Why are the inline-block elements misaligned? How to solve this problem? Apr 04, 2025 pm 10:39 PM

Regarding the reasons and solutions for misaligned display of inline-block elements. When writing web page layout, we often encounter some seemingly strange display problems. Compare...

How to use the clip-path attribute of CSS to achieve the 45-degree curve effect of segmenter? How to use the clip-path attribute of CSS to achieve the 45-degree curve effect of segmenter? Apr 04, 2025 pm 11:45 PM

How to achieve the 45-degree curve effect of segmenter? In the process of implementing the segmenter, how to make the right border turn into a 45-degree curve when clicking the left button, and the point...

How to customize the resize symbol through CSS and make it uniform with the background color? How to customize the resize symbol through CSS and make it uniform with the background color? Apr 05, 2025 pm 02:30 PM

The method of customizing resize symbols in CSS is unified with background colors. In daily development, we often encounter situations where we need to customize user interface details, such as adjusting...

The latest price of Bitcoin in 2018-2024 USD The latest price of Bitcoin in 2018-2024 USD Feb 15, 2025 pm 07:12 PM

Real-time Bitcoin USD Price Factors that affect Bitcoin price Indicators for predicting future Bitcoin prices Here are some key information about the price of Bitcoin in 2018-2024:

How to compatible with multi-line overflow omission on mobile terminal? How to compatible with multi-line overflow omission on mobile terminal? Apr 05, 2025 pm 10:36 PM

Compatibility issues of multi-row overflow on mobile terminal omitted on different devices When developing mobile applications using Vue 2.0, you often encounter the need to overflow text...

How to achieve segmentation effect with 45 degree curve border? How to achieve segmentation effect with 45 degree curve border? Apr 04, 2025 pm 11:48 PM

Tips for Implementing Segmenter Effects In user interface design, segmenter is a common navigation element, especially in mobile applications and responsive web pages. ...

See all articles