您的位置:首页 > 编程语言 > Go语言

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

2014-11-16 00:00 841 查看
Android SDK的文档直接打开的话会很慢,而且不支持搜索。所以,本地搭建静态服务器是必要的。以下为引用的其他博客的资源,感谢作者。

首先,搭建一个静态的服务器 我写程序喜欢使用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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: