Welcome to the exciting world of web development in Go! In this chapter, we'll explore the net/http package, which is at the core of building web applications in Go. From understanding the basics to advanced techniques, we'll cover everything you need to know to harness the power of this package and create robust web servers and clients. Let's dive in!
The net/http
package is a part of the standard library in Go and provides essential functionalities for building HTTP servers and clients. It offers an elegant and efficient way to handle HTTP requests and responses, enabling developers to create web applications with ease.
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, World!")
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
http.HandleFunc()
registers a handler function for a specific route (“/” in this case).http.ListenAndServe()
starts an HTTP server on the specified port (8080) and uses the default router to handle incoming requests.
func aboutHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "About Page")
}
func contactHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Contact Page")
}
func main() {
http.HandleFunc("/", handler)
http.HandleFunc("/about", aboutHandler)
http.HandleFunc("/contact", contactHandler)
http.ListenAndServe(":8080", nil)
}
func handler(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
fmt.Fprintf(w, "GET Request")
} else if r.Method == "POST" {
fmt.Fprintf(w, "POST Request")
} else {
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
}
}
r.Method
to determine the HTTP method of the request.
func handler(w http.ResponseWriter, r *http.Request) {
name := r.URL.Query().Get("name")
fmt.Fprintf(w, "Hello, %s!", name)
}
r.URL.Query().Get()
to retrieve query parameters from the URL.
func logger(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println(r.Method, r.URL.Path)
next.ServeHTTP(w, r)
})
}
func main() {
http.Handle("/", logger(http.HandlerFunc(handler)))
http.ListenAndServe(":8080", nil)
}
Middleware functions intercept incoming requests and can perform tasks like logging, authentication, etc., before passing them to the main handler.
import "github.com/gorilla/mux"
func main() {
r := mux.NewRouter()
r.HandleFunc("/", handler)
r.HandleFunc("/products/{key}", productHandler)
http.Handle("/", r)
http.ListenAndServe(":8080", nil)
}
In this chapter, we've explored the net/http package in Go and learned how to build powerful HTTP servers and clients. From handling basic requests to implementing advanced features like middleware and routing, you now have the knowledge to create robust and scalable web applications in Go. Keep experimenting, exploring, and building amazing things with Go's net/http package! Happy coding !❤️