Fragment Description:



Setting http.Header and Getting back their value.

httpSetGetHeader

Last update, on 2015, Fri 9 Oct, 16:15:39

/* ... <== see fragment description ... */

package main

import (
    "flag"
    "fmt"
    "log"
    "net/http"
    "strconv"
)

var (
    port     int
    httpAddr string
)

func init() {
    flag.IntVar(&port, "port", 8080, "HTTP Server Port")
    flag.Parse()
    httpAddr = fmt.Sprintf(":%v", port)
}
func main() {
    http.HandleFunc("/", rootHandler)
    log.Printf("Listening to %v", httpAddr)
    log.Fatal(http.ListenAndServe(httpAddr, nil))
}
func rootHandler(w http.ResponseWriter, r *http.Request) {
    // Get()
    ua := r.Header.Get("User-Agent")
    msg := fmt.Sprintf("Your user agent is: %v\n", ua)
    // Set()
    w.Header().Set("Content-Type", "text/plain")
    w.Header().Set("Content-Length", strconv.Itoa(len(msg)))
    fmt.Fprint(w, msg)
}



Comments