Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Handling HTTP Requests in Go with ServeMux and Handlers

Tech 1

Go's HTTP request processing revolves around two core components: ServeMux for routing and Handlers for response generation.

  • ServeMux acts as an HTTP request router, matching incoming requests against registered URL patterns and invoking the corresponding handler
  • Handlers implement the http.Handler interface by defining a ServeHTTP(http.ResponseWriter, *http.Request) method
package main

import (
  "log"
  "net/http"
)

func main() {
  router := http.NewServeMux()
  
  redirectHandler := http.RedirectHandler("https://example.com", http.StatusTemporaryRedirect)
  router.Handle("/old-path", redirectHandler)
  
  log.Println("Server starting on :8080")
  http.ListenAndServe(":8080", router)
}

This implementation:

  1. Creates a new ServeMux instance
  2. Registers a redircet handler for "/old-path"
  3. Starts the server on port 8080

Custom Handler Implementation

Here's a time-based handler that formats the current time:

type clockHandler struct {
  timeFormat string
}

func (ch *clockHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  currentTime := time.Now().Format(ch.timeFormat)
  w.Write([]byte("Current time: " + currentTime))
}

Function Handlers

For simpler cases, standard functions can be converted to handlers:

func showTime(w http.ResponseWriter, r *http.Request) {
  now := time.Now().Format(time.RFC1123)
  w.Write([]byte("Time now: " + now))
}

func main() {
  mux := http.NewServeMux()
  mux.HandleFunc("/now", showTime)
  
  log.Println("Starting server...")
  http.ListenAndServe(":8080", mux)
}

The HandleFunc method provides a concise way to register function handlers.

Tags: go

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.