Menu Close

Go – Building an HTTP Handler Function in Go

In this article, we are going to learn Building an HTTP Handler Function in Go with an example.


Go is a popular programming language known for its simplicity, efficiency, and strong support for concurrent programming. One of its most commonly used features is its built-in HTTP package, which makes it easy to build web servers and clients. In this article, we’ll take a deep dive into building an HTTP handler function in Go and provide a detailed example to help you get started.

An HTTP handler in Go takes two arguments: a ResponseWriter and a pointer to a Request. The ResponseWriter is an interface that allows you to write the HTTP response, while the Request contains information about the incoming HTTP request, such as the method, URL, and headers.

To create an HTTP handler function in Go, you need to implement the http.Handler interface. This interface requires a single method, ServeHTTP, which has the following signature:

type Handler interface {
    ServeHTTP(ResponseWriter, *Request)

Creating a Simple HTTP Handler Function

Let’s create a simple HTTP handler function that responds with a “Hello, World!” message. We’ll start by implementing the ServeHTTP method:

package main

import (

type HelloHandler struct{}

func (h *HelloHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "Hello, World!")

func main() {
    handler := &HelloHandler{}
    http.Handle("/", handler)
    http.ListenAndServe(":8080", nil)

In this example, we define a HelloHandler struct and implement the ServeHTTP method for it. Inside ServeHTTP, we use the fmt.Fprint function to write the “Hello, World!” message to the response writer. Finally, in the main function, we create an instance of HelloHandler, register it for the root path (“/”), and start the HTTP server on port 8080.

Handling Different HTTP Methods

func (h *HelloHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    switch r.Method {
    case http.MethodGet:
        fmt.Fprint(w, "Hello, World! (GET)")
    case http.MethodPost:
        fmt.Fprint(w, "Hello, World! (POST)")
        fmt.Fprint(w, "Method not allowed")

In this example, we use a switch statement to check the request method and respond with a different message for each supported method (GET and POST). If the method is not supported, we set the response status code to StatusMethodNotAllowed (405) and return an error message.

Parsing Query Parameters

Query parameters are a fundamental component of HTTP requests, allowing clients to pass data to a server in a structured manner. In the Go programming language, you can easily parse query parameters within HTTP handle functions.

package main

import (

func handleRequest(w http.ResponseWriter, r *http.Request) {
	// Parse query parameters
	params := r.URL.Query()

	// Extract specific parameters
	name := params.Get("name")
	ageParam := params.Get("age")

	// Convert age to integer
	age, err := strconv.Atoi(ageParam)
	if err != nil {
		http.Error(w, "Invalid age parameter", http.StatusBadRequest)

	// Process the query parameters (e.g., save them to a database, etc.)

	// Send a response to the client
	fmt.Fprintf(w, "Hello, %s! You are %d years old.", name, age)

func main() {
	http.HandleFunc("/parse", handleRequest)

	// Start the HTTP server
	port := ":8080"
	fmt.Printf("Starting server on port %s\n", port)
	if err := http.ListenAndServe(port, nil); err != nil {
		fmt.Printf("Error starting server: %v\n", err)

In this example, we first parse the query parameters using r.URL.Query(), which returns a url.Values map. We then extract the “name” and “age” parameters using the Get method.

The “age” parameter is then converted from a string to an integer using strconv.Atoi(). If an error occurs during the conversion, we send a “Bad Request” status to the client and return immediately.

Finally, we send a response back to the client using fmt.Fprintf().

To check more leetcode problem’s solution. Pls click given below link:

Posted in golang, net, packages

Leave a Reply

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