How do you create an HTTP server in Go?

To create an HTTP server in Go, you can use the "net/http" package provided by the Go standard library. Here's a basic example of how to create an HTTP server in Go:
HTTP server in Go

Example

package main

import (
	"fmt"
	"net/http"
)

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Hello, World!")
	})

	if err := http.ListenAndServe(":8080", nil); err != nil {
		panic(err)
	}
}

In this example, we first import the "net/http" and "fmt" packages. We then define an anonymous function as an HTTP request handler that writes the string "Hello, World!" to the HTTP response writer. We use the "http.HandleFunc" function to register this handler function to handle requests to the root URL path ("/").

Finally, we use the "http.ListenAndServe" function to start the HTTP server listening on port 8080. The second argument to "http.ListenAndServe" is set to "nil" because we're using the default HTTP server implementation provided by the "net/http" package. If an error occurs, such as if the port is already in use, "http.ListenAndServe" will return an error value that we can handle as appropriate.

You can run this program by saving it as a ".go" file, such as "main.go", and then running the command "go run main.go" in the terminal. Once the server is running, you can access it by visiting "http://localhost:8080/" in a web browser or using an HTTP client tool such as "curl" or "Postman".


Most Helpful This Week