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:
- 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))
}
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))
}
Personally i prefer the handle function as it is much easier to write
Top comments (0)