Last active
September 22, 2022 20:31
-
-
Save codenoid/ee0d58e3bfc18cde2d4f5bca67617d08 to your computer and use it in GitHub Desktop.
Golang Upload -> Resize -> Return modified image
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
curl -F "[email protected]" http://localhost:8080/upload --output result.jpg |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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