Saturday, July 19, 2014

Golang web server: basic operatons using gorilla/mux [download,url variables,filtering url]

must see built-in basic operations: http://noypi-linux.blogspot.com/2014/07/golang-web-server-basic-operatons-using.html

sample project: https://github.com/noypi/golang-samples/tree/master/webserver-gorilla

- url variables

 r := mux.NewRouter()  
 r.HandleFunc("/get/{html}", GetHandler).Methods("GET")  
 http.Handle("/", r)  
 // wait for clients  
 http.ListenAndServe(":8083", nil)  
 ...  
 ...  
 func GetHandler(res http.ResponseWriter, req *http.Request) {  
      vars := mux.Vars(req)  
      html := vars["html"]  

- url filtering

Example below will...
allow "/download/download12/txt"
and disallows "/download/notdownload/txt"

Because the filter requires input having lowercase characters before the 0 to 9 numerals...
 r := mux.NewRouter()  
 // try to filter files to download, example only  
 r.HandleFunc("/download/{name:[a-z]+[0-9]+}/{ext}", DownloadHandler)  
 http.Handle("/", r)  
 // wait for clients  
 http.ListenAndServe(":8083", nil)  
 ...  
 ...  
 func DownloadHandler(res http.ResponseWriter, req *http.Request) {  
      vars := mux.Vars(req)  
      name := vars["name"]  
      ext := vars["ext"]  


- download handler

 import (  
      "github.com/gorilla/mux"  
      "net/http"  
      "path"  
 )  
 func DownloadHandler(res http.ResponseWriter, req *http.Request) {  
      var (  
           status int  
           err  error  
      )  
      defer func() {  
           if nil != err {  
                http.Error(res, err.Error(), status)  
           }  
      }()  
      // r.HandleFunc("/download/{name:[a-z]+[0-9]+}/{ext}", DownloadHandler)  
      vars := mux.Vars(req)  
      name := vars["name"]  
      ext := vars["ext"]  
      // use path.Base(), might prevent directory traversal attack  
      fpath := "./static/fileserver/" + path.Base(name+"."+ext)  
      if err = servefile(res, fpath); nil != err {  
           status = http.StatusInternalServerError  
           return  
      }  
 }