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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)