github.com/egonelbre/exp@v0.0.0-20240430123955-ed1d3aa93911/server-timing/main.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  	"net/http"
     7  )
     8  
     9  func main() {
    10  	http.HandleFunc("/", basic)
    11  	http.HandleFunc("/trailing", trailing)
    12  	http.HandleFunc("/send-trailers-example", trailers_examples)
    13  	http.ListenAndServe(":3030", nil)
    14  }
    15  
    16  func basic(w http.ResponseWriter, r *http.Request) {
    17  	w.Header().Set("Server-Timing", `database; dur=1.9; desc="Database Request",render; dur=2.6; desc="Render"`)
    18  
    19  	w.WriteHeader(http.StatusOK)
    20  	fmt.Fprintln(w, "<body><h1>Hello World</h1></body>")
    21  }
    22  
    23  func trailing(w http.ResponseWriter, r *http.Request) {
    24  	w.Header().Set("Trailer", "Server-Timing")
    25  
    26  	w.WriteHeader(http.StatusOK)
    27  	fmt.Fprintln(w, "<body><h1>Hello World</h1></body>")
    28  
    29  	w.Header().Set("Server-Timing", `database; dur=1.9; desc="Database Request",render; dur=2.6; desc="Render"`)
    30  }
    31  
    32  func trailers_examples(w http.ResponseWriter, req *http.Request) {
    33  	// Before any call to WriteHeader or Write, declare
    34  	// the trailers you will set during the HTTP
    35  	// response. These three headers are actually sent in
    36  	// the trailer.
    37  	w.Header().Set("Trailer", "AtEnd1, AtEnd2")
    38  	w.Header().Add("Trailer", "AtEnd3")
    39  
    40  	w.Header().Set("Content-Type", "text/plain; charset=utf-8") // normal header
    41  	w.WriteHeader(http.StatusOK)
    42  
    43  	w.Header().Set("AtEnd1", "value 1")
    44  	io.WriteString(w, "This HTTP response has both headers before this text and trailers at the end.\n")
    45  	w.Header().Set("AtEnd2", "value 2")
    46  	w.Header().Set("AtEnd3", "value 3") // These will appear as trailers.
    47  }