Go语言实现简单的一个静态WEB服务器

jopen 9年前

首先,搭建一个静态的服务器 我写程序喜欢使用HTML通过AJAX发送JSON请求到后端处理。 HttpServer.go 代码如下:

package main  import (          "flag"          "io/ioutil"          "log"          "net/http"          "os"          "strings"  )    var realPath *string    func staticResource(w http.ResponseWriter, r *http.Request) {          path := r.URL.Path          request_type := path[strings.LastIndex(path, "."):]          switch request_type {          case ".css":                  w.Header().Set("content-type", "text/css")          case ".js":                  w.Header().Set("content-type", "text/javascript")          default:          }           fin, err := os.Open(*realPath + path)          defer fin.Close()          if err != nil {                  log.Fatal("static resource:", err)          }           fd, _ := ioutil.ReadAll(fin)          w.Write(fd)  }    func main() {          realPath = flag.String("path", "", "static resource path")          flag.Parse()          http.HandleFunc("/", staticResource)          err := http.ListenAndServe(":8080", nil)          if err != nil {                  log.Fatal("ListenAndServe:", err)          }   }

更BT的方法:

package main  import (          "net/http"  )  func main() {          http.Handle("/", http.FileServer(http.Dir("/tmp/static/")))          http.ListenAndServe(":8080", nil)  }

将EasyUI前端框架解压到 /tmp/static 目录下:

在GOPATH下执行

go run HttpServer.go --path=/tmp/static