Saturday, July 19, 2014

Golang web server: basic operatons using built-in net/http [multiple file upload,static,robots.txt,favicon.ico]

must see examples using gorilla/mux: http://noypi-linux.blogspot.com/2014/07/golang-web-server-basic-operatons-using_19.html

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

- redirect handler

      // redirect  
      http.Handle("/some/404/path/redirect/to/robots.txt", http.RedirectHandler("/robots.txt", http.StatusMovedPermanently))  


- robots.txt, favicon.ico

 ...  
      // serve a file  
      http.HandleFunc("/favicon.ico", ServeFileHandler)  
      http.HandleFunc("/robots.txt", ServeFileHandler)  
      http.HandleFunc("/other/path/robots.txt", ServeFileHandler)  
 ...  
 func ServeFileHandler(res http.ResponseWriter, req *http.Request) {  
      fname := path.Base(req.URL.Path)  
      http.ServeFile(res, req, "./static/files/"+fname)  
 }  

- upload handler

 package main  
 import (  
      "io"  
      "mime/multipart"  
      "net/http"  
      "os"  
      "strconv"  
 )  
 func UploadHandler(res http.ResponseWriter, req *http.Request) {  
      var (  
           status int  
           err  error  
      )  
      defer func() {  
           if nil != err {  
                http.Error(res, err.Error(), status)  
           }  
      }()  
      // parse request  
      const _24K = (1 << 20) * 24  
      if err = req.ParseMultipartForm(_24K); nil != err {  
           status = http.StatusInternalServerError  
           return  
      }  
      for _, fheaders := range req.MultipartForm.File {  
           for _, hdr := range fheaders {  
                // open uploaded  
                var infile multipart.File  
                if infile, err = hdr.Open(); nil != err {  
                     status = http.StatusInternalServerError  
                     return  
                }  
                // open destination  
                var outfile *os.File  
                if outfile, err = os.Create("./uploaded/" + hdr.Filename); nil != err {  
                     status = http.StatusInternalServerError  
                     return  
                }  
                // 32K buffer copy  
                var written int64  
                if written, err = io.Copy(outfile, infile); nil != err {  
                     status = http.StatusInternalServerError  
                     return  
                }  
                res.Write([]byte("uploaded file:" + hdr.Filename + ";length:" + strconv.Itoa(int(written))))  
           }  
      }  
 }