How To Make an HTTP Server in Golang?

An HTTP server is a software program that listens for and responds to requests from clients over the internet or a local network. The most common type of HTTP server is a web server, which serves web pages and other files to clients using the HTTP protocol. When a client, such as a web browser, requests a page or file from an HTTP server, the server sends a response, which may include the requested file, an error message, or a redirect to another page.
HTTP Server
Here's an example of how to create an HTTP server in Go (also known as Golang):

Example

package main

import (
    "fmt"
    "net/http"
)

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

    http.ListenAndServe(":8080", nil)
}
In this example, we are using the net/http package to create an HTTP server. The http.HandleFunc function sets up a handler for the root ("/") path of our server. The handler is a function that takes an http.ResponseWriter and an *http.Request as its arguments. In this case, we are using the fmt.Fprintf function to write "Hello, World!" to the response writer.

We then call http.ListenAndServe to start the server and listen on port 8080. The second argument to ListenAndServe is the handler to use, in this case we pass nil as we have already set up our handler using http.HandleFunc.

You can run the server by running the above code with go run command and hitting http://localhost:8080 in browser to check if the server is running and able to respond with Hello, World!.

Most Helpful This Week