create a http server and upload a file and return a json response in go

main.go
package main

import (
	"encoding/json"
	"io"
	"log"
	"net/http"
	"os"
)

type Response struct {
	Message string `json:"message"`
	Status  int    `json:"status"`
}

func uploadHandler(w http.ResponseWriter, r *http.Request) {
	// Parse the multipart form in the request
	err := r.ParseMultipartForm(1024)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		json.NewEncoder(w).Encode(Response{Message: "Error parsing request body", Status: http.StatusInternalServerError})
		return
	}

	// Get a handle to the uploaded file
	file, header, err := r.FormFile("file")
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		json.NewEncoder(w).Encode(Response{Message: "Error getting file", Status: http.StatusBadRequest})
		return
	}
	defer file.Close()

	// Create a new file on the server to store the uploaded file
	newFile, err := os.Create(header.Filename)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		json.NewEncoder(w).Encode(Response{Message: "Error creating file", Status: http.StatusInternalServerError})
		return
	}
	defer newFile.Close()

	// Copy the uploaded file to the destination file
	_, err = io.Copy(newFile, file)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		json.NewEncoder(w).Encode(Response{Message: "Error copying file", Status: http.StatusInternalServerError})
		return
	}

	// Return a success message
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(Response{Message: "File uploaded successfully", Status: http.StatusOK})
}

func main() {
	http.HandleFunc("/upload", uploadHandler)
	log.Fatal(http.ListenAndServe(":8080", nil))
}
1623 chars
60 lines

This code creates an HTTP server using the net/http package. It defines a Response struct which will be encoded to JSON and returned to the client. The uploadHandler function handles requests to the /upload endpoint. It uses r.FormFile to get a handle to the uploaded file, creates a new file on the server, and copies the uploaded file to the new file. If any errors occur, an error response will be returned. If the file is uploaded successfully, a success response will be returned.

related categories

gistlibby LogSnag