Menu Close

Go – HTTP Serve Function in Go

In this article, we will explore the http Serve function in Go net/http package in detail, along with examples.

Introduction:

The HTTP Serve function is a core feature of the Go programming language (also known as Golang) for building web applications and APIs. This function allows you to create an HTTP server that can listen for incoming requests and respond to them accordingly. In this article, we will discuss the http.Serve function in Go, provide examples, and delve into its usage and details.

Understanding the http.Serve Function

The http.Serve function is part of the net/http package in the Go standard library. Its primary purpose is to create an HTTP server that can serve incoming requests using a specified net.Listener and http.Handler. The function signature is:

func Serve(l net.Listener, handler http.Handler) error
  • l (net.Listener): An interface that represents a network listener that can accept incoming network connections.
  • handler (http.Handler): An interface that defines the ServeHTTP method, which is responsible for handling incoming HTTP requests and generating appropriate responses.
  • The function returns an error if there’s an issue with the server, such as a problem with the Listener or if the server is closed manually.

Using http.Serve in Go

Here’s an example of using http.Serve to create a simple HTTP server that listens on port 8080 and responds with “Hello, Gophers!” to every incoming request:

package main

import (
	"fmt"
	"net/http"
	"net"
)

type myHandler struct{}

func (h *myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	fmt.Fprint(w, "Hello, Gophers!")
}

func main() {
	listener, err := net.Listen("tcp", ":8080")
	if err != nil {
		panic(err)
	}

	handler := &myHandler{}

	fmt.Println("Starting server on :8080")
	if err := http.Serve(listener, handler); err != nil {
		panic(err)
	}
}

In this example, we first create a net.Listener on port 8080 using the net.Listen function. We then define a custom http.Handler by creating a new struct called myHandler and implementing the ServeHTTP method. Inside the ServeHTTP method, we write a “Hello, Gophers!” response to the http.ResponseWriter.

Finally, in the main function, we pass the listener and handler to the http.Serve function, which starts the HTTP server. The server will run until it encounters an error or is closed manually.

Using http.Serve with http.DefaultServeMux

In most cases, it’s more convenient to use the http.HandleFunc and http.ListenAndServe functions instead of directly working with http.Serve. These functions utilize the http.DefaultServeMux, which is a default instance of http.ServeMux, a built-in HTTP request multiplexer in the net/http package.

Here’s an example of using http.HandleFunc and http.ListenAndServe to create a simple HTTP server:

package main

import (
	"fmt"
	"net/http"
)

func helloHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprint(w, "Hello, Gophers!")
}

func main() {
	http.HandleFunc("/", helloHandler)
	fmt.Println("Starting server on :8080")
	if err := http.ListenAndServe(":8080", nil); err != nil {
		panic(err)
	}
}

In this example, we use http.HandleFunc to register our helloHandler function for the root path (“/”). Then, we use http.ListenAndServe to start the server on port 8080 with the http.DefaultServeMux.

Conclusion

The http.Serve function in Go enables you to create HTTP servers that can handle incoming requests and generate responses. By understanding its usage and combining it with the net

To check more Go related articles. Pls click given below link:

https://www.techieindoor.com/category/leetcode/

Posted in golang, net, packages

Leave a Reply

Your email address will not be published. Required fields are marked *