create a http server with a custom route in go

To create a custom route in a Go HTTP server, we can use the http.HandleFunc() function to register a route and its corresponding handler function.

Here's an example:

main.go
package main

import (
	"fmt"
	"net/http"
)

func main() {
	// Define the route and its handler function
	http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Hello World!")
	})

	// Start the server on port 8080
	fmt.Println("Starting server on port 8080")
	http.ListenAndServe(":8080", nil)
}
333 chars
18 lines

In this example, we've defined a custom route /hello and its handler function, which simply writes Hello World! to the response writer w.

We then start the server on port 8080 using the http.ListenAndServe() function.

We can test our custom route by visiting http://localhost:8080/hello in a browser or by sending a GET request to it using a tool like curl.

related categories

gistlibby LogSnag