How to Build an Image Processing Service in Go

Web
Build a Go image processing service by creating an HTTP handler that decodes uploaded images and re-encodes them using the standard library.

Build an image processing service in Go by creating an HTTP server that accepts image uploads, processes them using the image package, and returns the result.

package main

import (
	"image"
	"image/jpeg"
	"io"
	"net/http"
	"os"
)

func processImage(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}
	file, _, err := r.FormFile("image")
	if err != nil {
		http.Error(w, "Upload failed", http.StatusBadRequest)
		return
	}
	defer file.Close()
	img, _, err := image.Decode(file)
	if err != nil {
		http.Error(w, "Decode failed", http.StatusBadRequest)
		return
	}
	out, err := os.CreateTemp("", "processed-*")
	if err != nil {
		http.Error(w, "Temp file failed", http.StatusInternalServerError)
		return
	}
	defer os.Remove(out.Name())
	if err := jpeg.Encode(out, img, nil); err != nil {
		http.Error(w, "Encode failed", http.StatusInternalServerError)
		return
	}
	out.Seek(0, io.SeekStart)
	http.ServeFile(w, r, out.Name())
}

func main() {
	http.HandleFunc("/process", processImage)
	http.ListenAndServe(":8080", nil)
}