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)) } }
解决方法
我想花点时间将这些评论扩展为答案。
首先,正如我们已经讨论过的,您没有使用正确的 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)
我们看到以下内容:
{ "status": false, "error": { "message": "no file chosen.", "type": "error_file_not_provided", "code": 10 } }
我们收到此错误是因为您没有在 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" } } } } }
请注意,没有 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 } }
这不是 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"` } )
然后解组响应如下所示:
var result anonfilesresponse err = json.unmarshal(body, &result)
我们可以请求以下字段:
fmt.Printf("URL: %s\n", result.Data.File.URL.Full)
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!

Mastering the strings package in Go language can improve text processing capabilities and development efficiency. 1) Use the Contains function to check substrings, 2) Use the Index function to find the substring position, 3) Join function efficiently splice string slices, 4) Replace function to replace substrings. Be careful to avoid common errors, such as not checking for empty strings and large string operation performance issues.

You should care about the strings package in Go because it simplifies string manipulation and makes the code clearer and more efficient. 1) Use strings.Join to efficiently splice strings; 2) Use strings.Fields to divide strings by blank characters; 3) Find substring positions through strings.Index and strings.LastIndex; 4) Use strings.ReplaceAll to replace strings; 5) Use strings.Builder to efficiently splice strings; 6) Always verify input to avoid unexpected results.

ThestringspackageinGoisessentialforefficientstringmanipulation.1)Itofferssimpleyetpowerfulfunctionsfortaskslikecheckingsubstringsandjoiningstrings.2)IthandlesUnicodewell,withfunctionslikestrings.Fieldsforwhitespace-separatedvalues.3)Forperformance,st

WhendecidingbetweenGo'sbytespackageandstringspackage,usebytes.Bufferforbinarydataandstrings.Builderforstringoperations.1)Usebytes.Bufferforworkingwithbyteslices,binarydata,appendingdifferentdatatypes,andwritingtoio.Writer.2)Usestrings.Builderforstrin

Go's strings package provides a variety of string manipulation functions. 1) Use strings.Contains to check substrings. 2) Use strings.Split to split the string into substring slices. 3) Merge strings through strings.Join. 4) Use strings.TrimSpace or strings.Trim to remove blanks or specified characters at the beginning and end of a string. 5) Replace all specified substrings with strings.ReplaceAll. 6) Use strings.HasPrefix or strings.HasSuffix to check the prefix or suffix of the string.

Using the Go language strings package can improve code quality. 1) Use strings.Join() to elegantly connect string arrays to avoid performance overhead. 2) Combine strings.Split() and strings.Contains() to process text and pay attention to case sensitivity issues. 3) Avoid abuse of strings.Replace() and consider using regular expressions for a large number of substitutions. 4) Use strings.Builder to improve the performance of frequently splicing strings.

Go's bytes package provides a variety of practical functions to handle byte slicing. 1.bytes.Contains is used to check whether the byte slice contains a specific sequence. 2.bytes.Split is used to split byte slices into smallerpieces. 3.bytes.Join is used to concatenate multiple byte slices into one. 4.bytes.TrimSpace is used to remove the front and back blanks of byte slices. 5.bytes.Equal is used to compare whether two byte slices are equal. 6.bytes.Index is used to find the starting index of sub-slices in largerslices.

Theencoding/binarypackageinGoisessentialbecauseitprovidesastandardizedwaytoreadandwritebinarydata,ensuringcross-platformcompatibilityandhandlingdifferentendianness.ItoffersfunctionslikeRead,Write,ReadUvarint,andWriteUvarintforprecisecontroloverbinary


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 Chinese version
Chinese version, very easy to use

SublimeText3 Mac version
God-level code editing software (SublimeText3)
