Saturday, July 12, 2014

How to set the header in server response

Say you want to create a simple web site. Really simple - a "Hello world" site.

The site has just one page '/' and in this one page it shows just "Hello world" inside a <div> tag, with a border.

So create your file system in this structure:
- site.com
  - css
    - style.css
  - tpl
    - main.tpl.html
  - hello.go

In hello.go we will have our server listening for requests:




package main

import (
 "fmt"
 "html/template"
 "io/ioutil"
 "net/http"
 "os"
 "path/filepath"
)

// Deliver front page. use main.tpl.html template.
func handler(w http.ResponseWriter, r *http.Request) {
 t, _ := template.ParseFiles("tpls/main.tpl.html")
 t.Execute(w, "hello")
}

// Deliver css files. This will not work without the 
// 'Content-Type:text/css' header.
func fileLoadHandler(w http.ResponseWriter, r *http.Request) {
 baseDir, _ := filepath.Abs(filepath.Dir(os.Args[0]))
 fileName := r.URL.Path
 file, err := ioutil.ReadFile(fmt.Sprintf("%s%s", baseDir, fileName))

 // Here we set the header.. Without this the browser
 // won't use you css
 w.Header().Set("Content-Type", "text/css")
 fmt.Fprint(w, string(file))
 if err != nil {
  fmt.Println("Error reading file: ")
  fmt.Println(err)
 }
}


func main() {
 
 // front page handler
 http.HandleFunc("/", handler)

 // handler to load css
 http.HandleFunc("/css/", fileLoadHandler)

 // Start server on localhost:8002
 err = http.ListenAndServe(":8002", nil)
 if err != nil {
  fmt.Println("error:   ")
  fmt.Println(err)
 }
}

Take a look at the

func fileLoadHandler(w http.ResponseWriter, r *http.Request)
function. More specific look at this line


w.Header().Set("Content-Type", "text/css")
The w.Header() returns a map of [string]string i.e the key is string and the value is string
and the w.Header() has a Set() function to set a new value. So to set a new Header in the response just use w.Header().Set("<header key>", "<header value>")