Menu Close

Go – HTTP ListenAndServeTLS Function in Go

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

Introduction:

Go, also known as Golang, is a statically typed, compiled programming language known for its simplicity, efficient performance, and strong concurrency support. Go’s standard library provides the net/http package, which simplifies the process of creating HTTP servers. In this article, we will delve into the http.ListenAndServeTLS function, which is used to create HTTPS servers that serve content over secure connections.

Understanding the http.ListenAndServeTLS Function

The http.ListenAndServeTLS function is a part of Go’s net/http package. It allows developers to create an HTTPS server that listens for incoming connections, serves HTTP responses, and secures communication using TLS (Transport Layer Security). This function starts an HTTPS server on a specified address and port and routes incoming requests to appropriate handlers.

syntax

func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error

Parameters:

  • addr: The address and port on which the server should listen for incoming connections (e.g., “localhost:8443” or “:8443”).
  • certFile: The path to the TLS certificate file.
  • keyFile: The path to the TLS private key file.
  • handler: An object implementing the http.Handler interface, responsible for handling incoming requests and generating responses. If nil, the http.DefaultServeMux is used.

Example:

Let’s create a simple HTTPS server using the ListenAndServeTLS function. We will serve a basic “Hello, World!” response to any incoming requests.

First, ensure that you have a valid TLS certificate and private key. For this example, we will use self-signed certificates generated using the OpenSSL command line tool:

openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes

Example 1:

package main

import (
    "fmt"
    "net/http"
)

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

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/", helloHandler)

    server := &http.Server{
        Addr:    ":8443",
        Handler: mux,
    }

    fmt.Println("Starting HTTPS server on https://localhost:8443")
    err := server.ListenAndServeTLS("cert.pem", "key.pem")
    
    if err != nil && err != http.ErrServerClosed {
        fmt.Printf("Error starting HTTPS server: %v\n", err)
    }
}

Example 2:

package main

import (
	"fmt"
	"net/http"
)

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Welcome to the Golang HTTPS Server!")
	})

	err := http.ListenAndServeTLS(":8443", "cert.pem", "key.pem", nil)
	if err != nil {
		fmt.Printf("Failed to start server: %v\n", err)
	}
}

Build and run the server:

go build main.go
./main

Conclusion

In this article, we have examined the ListenAndServeTLS function in Go’s ‘net/http’ package. This function makes it easy to create HTTPS servers that serve HTTP requests over secure TLS connections. By providing a simple example, we demonstrated how to use the function to build a basic secure server. With this knowledge, you can now create more complex and secure web applications in Go.

To check more leetcode problem’s solution. 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 *