How to create a custom HTTP server with routing and request handling in Go?

To create a custom HTTP server with routing and request handling in Go, you can use the net/http package. Below is an example of how you can achieve this:

  1. Import the required packages:
import ( "fmt" "log" "net/http" )
  1. Define a handler function for each route that you want to handle:
func homeHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Welcome to the Home Page!") } func aboutHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "This is the About Page!") }
  1. Create a router function that maps each route to its respective handler:
func router() *http.ServeMux { mux := http.NewServeMux() mux.HandleFunc("/", homeHandler) mux.HandleFunc("/about", aboutHandler) return mux }
  1. Create a main function that starts the server and listens on a specified port:
func main() { server := &http.Server{ Addr: ":8080", Handler: router(), } log.Println("Server started on http://localhost:8080") log.Fatal(server.ListenAndServe()) }
  1. Run the main function to start the server.

Now, when you access http://localhost:8080, you will see the "Welcome to the Home Page!" message, and when you access http://localhost:8080/about, you will see the "This is the About Page!" message.

This example demonstrates the basic setup for creating a custom HTTP server with routing and request handling in Go. You can expand on this by adding more routes and handlers as per your requirements.