create a http server with a put route in go

To create a HTTP server with a PUT route in Go, you can use the built-in net/http package. Here's an example code:

main.go
package main

import (
	"fmt"
	"net/http"
)

func putHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method == "PUT" {
		fmt.Fprintf(w, "This is a PUT request")
	} else {
		fmt.Fprintf(w, "Invalid request method")
	}
}

func main() {
	http.HandleFunc("/put", putHandler)

	fmt.Println("Starting server on :8080")
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		fmt.Println("Error starting server:", err)
	}
}
430 chars
25 lines

In this code, we define a putHandler function that checks if the HTTP method is PUT, and returns a message accordingly. We then register this handler function with the /put route in our main function using http.HandleFunc.

Finally, we start the server by calling http.ListenAndServe(":8080", nil) and passing in nil as the handler since we've already registered it with http.HandleFunc.

Now, if you make a PUT request to http://localhost:8080/put, you should see the message "This is a PUT request" in your browser or API client.

gistlibby LogSnag