DEV Community

Cover image for Handling Incoming HTTP Requests In GO
AI_Dosage
AI_Dosage

Posted on • Edited on

7 1

Handling Incoming HTTP Requests In GO

Go is a very powerful tool in the development of web services. In this article i will be covering how to handle HTTP Requests with Go.
Go has a powerful internal package http that provides HTTP client and server implementations.There are two ways to handle incoming HTTP Requests:

  1. Using The HTTP Handle func Handle(pattern string, handler Handler)

Handle registers the handler for the given pattern in the DefaultServeMux.

package main

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

type helloHandler struct {
   message string
}

func (h *helloHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
   w.Write([]byte(h.message))
}

func main() {
    http.Handle("/hello-handler", &helloHandler{message: 'hello world')
    log.Fatal(http.ListenAndServe(":8080", nil))
}
Enter fullscreen mode Exit fullscreen mode

2 . Using HTTP HandleFunc func HandleFunc(pattern string, handler func(ResponseWriter, *Request))

HandleFunc registers the handler function for the given pattern in the DefaultServeMux.

import (
    "log"
    "net/http"
)

func main() {
    hello := func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("Hello, world!, From a handleFunc"))
    }

    http.HandleFunc("/hello-handleFunc", hello)
    log.Fatal(http.ListenAndServe(":8080", nil))
}
Enter fullscreen mode Exit fullscreen mode

Personally i prefer the handle function as it is much easier to write

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up