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)
}
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
Most Helpful This Week
How to convert Go struct to JSON?How to Unmarshal nested JSON structure?Dereferencing a pointer from another packageHow do you write multi-line strings in Go?How to read names of all files and folders in current directory?How can I convert a string variable into Boolean, Integer or Float type in Golang?Strip all white spaces, tabs, newlines from a stringHigher Order Functions in GolangHow to import structs from another package in Go?Example to compare Println vs Printf