create a http server with a delete route in go

Here's an example code to create a HTTP server with a DELETE route in Go:

main.go
package main

import (
    "fmt"
    "log"
    "net/http"
)

func main() {
    // Create a new HTTP server
    server := &http.Server{Addr: ":8080"}

    // Define a /delete route that only responds to DELETE requests
    http.HandleFunc("/delete", func(w http.ResponseWriter, r *http.Request) {
        if r.Method == http.MethodDelete {
            // Handle the DELETE request
            fmt.Fprintln(w, "This resource has been deleted.")
        } else {
            // Return HTTP 405 Method Not Allowed for other request methods
            w.WriteHeader(http.StatusMethodNotAllowed)
            fmt.Fprintln(w, "Invalid request method.")
        }
    })

    // Start the server
    log.Fatal(server.ListenAndServe())
}
729 chars
28 lines

This code creates a new HTTP server running on port 8080. It defines a /delete route that only responds to DELETE requests, returning a message indicating that the resource has been deleted. If any other request method is used, it returns a HTTP 405 Method Not Allowed status code with an error message.

To test this server, you can run it and send a DELETE request to the /delete route using tools like curl or Postman.

related categories

gistlibby LogSnag