Skip to content

Instantly share code, notes, and snippets.

@codenoid
Last active September 22, 2022 20:31
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codenoid/ee0d58e3bfc18cde2d4f5bca67617d08 to your computer and use it in GitHub Desktop.
Save codenoid/ee0d58e3bfc18cde2d4f5bca67617d08 to your computer and use it in GitHub Desktop.
Golang Upload -> Resize -> Return modified image
curl -F "file=@input.jpg" http://localhost:8080/upload --output result.jpg
package main
import (
"fmt"
"io/ioutil"
"net/http"
"os"
"github.com/h2non/bimg"
)
func uploadFile(w http.ResponseWriter, r *http.Request) {
fmt.Println("File Upload Endpoint Hit")
// Parse our multipart form, 10 << 20 specifies a maximum
// upload of 10 MB files.
r.ParseMultipartForm(10 << 20)
// FormFile returns the first file for the given key `myFile`
// it also returns the FileHeader so we can get the Filename,
// the Header and the size of the file
file, handler, err := r.FormFile("file")
if err != nil {
fmt.Println("Error Retrieving the File")
fmt.Println(err)
return
}
defer file.Close()
byteContainer, err := ioutil.ReadAll(file)
newImage, err := bimg.NewImage(byteContainer).Resize(320, 240)
if err != nil {
fmt.Fprintln(os.Stderr, err)
}
w.Header().Set("Content-Type", handler.Header["Content-Type"][0])
w.Write(newImage)
}
func setupRoutes() {
http.HandleFunc("/upload", uploadFile)
http.ListenAndServe(":8080", nil)
}
func main() {
fmt.Println("Hello World")
setupRoutes()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment