create a http server with a specific route and a specific status code in go

You can create a HTTP server in Go by using the net/http package. Here's an example that shows how to create a server with a specific route and a specific status code:

main.go
package main

import (
	"fmt"
	"net/http"
)

func main() {
	// Define the handler function for the route
	http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
		// Set the status code to 200
		w.WriteHeader(http.StatusOK)

		// Write the response body
		fmt.Fprint(w, "Hello World!")
	})

	// Start the server on port 8080
	if err := http.ListenAndServe(":8080", nil); err != nil {
		panic(err)
	}
}
420 chars
23 lines

In this example, we define a handler function for the /hello route. Inside the handler, we set the status code to http.StatusOK before writing the response body using fmt.Fprint(). Finally, we start the server by calling http.ListenAndServe() and passing in the handler function.

gistlibby LogSnag