Go Web Development with net/http
Introduction
Go's net/http package provides everything needed to build reliable and fast web servers with
minimal dependencies.
Setting Up a Simple Web Server
package main
import (
"fmt"
"net/http"
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Welcome to Go Web Server!")
func main() {
http.HandleFunc("/", handler)
fmt.Println("Server is running at http://localhost:8080")
http.ListenAndServe(":8080", nil)
Routing Basics
http.HandleFunc("/about", aboutHandler)
http.HandleFunc("/contact", contactHandler)
Serving Static Files
fs := http.FileServer(http.Dir("./static"))
http.Handle("/static/", http.StripPrefix("/static/", fs))
Handling Forms and Query Params
func formHandler(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
fmt.Fprintf(w, "ParseForm() err: %v", err)
return
name := r.FormValue("name")
fmt.Fprintf(w, "Hello %s", name)
Middleware and Logging
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println(r.RequestURI)
next.ServeHTTP(w, r)
})
JSON APIs with net/http
func apiHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"message": "Hello JSON!"})
}
Structuring a Go Web Project
/project
/handlers
home.go
about.go
/static
/templates
main.go
Deployment Tips
- Use systemd, Docker, or nginx
- Set proper timeouts in http.Server
- Consider HTTPS with Let's Encrypt
Additional Resources
- https://pkg.go.dev/net/http
- https://gobyexample.com/
- https://gowebexamples.com