ZBLOG

go package main import ( "fmt" "io/ioutil" "net/http" ) func main() { http.HandleFunc("/upload", uploadHandler) err := http.ListenAndServe(":8888", nil) if err != nil { fmt.Println("Server error:", err) } } func uploadHandler(w http.Re...

您需要对uploadHandler函数进行修改,以便在文件和信息保存成功后返回成功的响应。以下是修改后的代码示例:

package main

import (
	"fmt"
	"io/ioutil"
	"mime/multipart"
	"net/http"
)

func main() {
	http.HandleFunc("/upload", uploadHandler)
	err := http.ListenAndServe(":8888", nil)
	if err != nil {
		fmt.Println("Server error:", err)
	}
}

func uploadHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		w.WriteHeader(http.StatusMethodNotAllowed)
		return
	}

	file, handler, err := r.FormFile("file")
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		fmt.Fprint(w, "Failed to retrieve file from request.")
		return
	}
	defer file.Close()

	info := r.FormValue("info")
	saveFile(file, handler.Filename)
	saveInfo(info)

	response := struct {
		Status  int    `json:"status"`
		Message string `json:"message"`
	}{
		Status:  http.StatusOK,
        Message: "success",
    }
    
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusOK)
    json.NewEncoder(w).Encode(response)
}

func saveFile(file multipart.File, filename string) {
	data, err := ioutil.ReadAll(file)
	if err != nil {
        fmt.Println("Failed to read file data:", err)
        return
    }
    
    // 将文件保存在当前目录下
    filePath := "./" + filename
    
	err = ioutil.WriteFile(filePath, data, 0644)
	if err != nil {
        fmt.Println("Failed to save file:", err)
        return
    }
    
    fmt.Println("File saved:", filePath)
}

func saveInfo(info string) {
    infoFilePath := "./info.txt"

	err := ioutil.WriteFile(infoFilePath, []byte(info), 0644)
	if err != nil {
        fmt.Println("Failed to save info:", err)
		return
    }
    
    fmt.Println("Info saved:", infoFilePath)
}

以上代码在文件和信息保存成功后,将返回一个状态码为200、消息为”success”的JSON响应。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=16676

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?