Go语言实现简单的一个静态WEB服务器
package main import (
"net/http"
) func main() {
http.Handle("/", http.FileServer(http.Dir("./www/")))
http.ListenAndServe(":8123", nil)
}
在生成的EXE文件所在目录中创建www子目录,在该目录中放web静态文件。
以上是静态文件使用http.FileServer,那么动态文件则用http.HandleFunc
参考http://www.cnblogs.com/yjf512/archive/2012/09/03/2668384.html
或http://studygolang.com/articles/4105
或参考以下代码
package main import (
"bytes"
"expvar"
"flag"
"fmt"
"io"
"log"
"net/http"
"os"
"os/exec"
"strconv"
"sync"
) // hello world, the web server
var helloRequests = expvar.NewInt("hello-requests") func HelloServer(w http.ResponseWriter, req *http.Request) {
helloRequests.Add()
io.WriteString(w, "hello, world!\n")
} // Simple counter server. POSTing to it will set the value.
type Counter struct {
mu sync.Mutex // protects n
n int
} // This makes Counter satisfy the expvar.Var interface, so we can export
// it directly.
func (ctr *Counter) String() string {
ctr.mu.Lock()
defer ctr.mu.Unlock()
return fmt.Sprintf("%d", ctr.n)
} func (ctr *Counter) ServeHTTP(w http.ResponseWriter, req *http.Request) {
ctr.mu.Lock()
defer ctr.mu.Unlock()
switch req.Method {
case "GET":
ctr.n++
case "POST":
buf := new(bytes.Buffer)
io.Copy(buf, req.Body)
body := buf.String()
if n, err := strconv.Atoi(body); err != nil {
fmt.Fprintf(w, "bad POST: %v\nbody: [%v]\n", err, body)
} else {
ctr.n = n
fmt.Fprint(w, "counter reset\n")
}
}
fmt.Fprintf(w, "counter = %d\n", ctr.n)
} // simple flag server
var booleanflag = flag.Bool("boolean", true, "another flag for testing") func FlagServer(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
fmt.Fprint(w, "Flags:\n")
flag.VisitAll(func(f *flag.Flag) {
if f.Value.String() != f.DefValue {
fmt.Fprintf(w, "%s = %s [default = %s]\n", f.Name, f.Value.String(), f.DefValue)
} else {
fmt.Fprintf(w, "%s = %s\n", f.Name, f.Value.String())
}
})
} // simple argument server
func ArgServer(w http.ResponseWriter, req *http.Request) {
for _, s := range os.Args {
fmt.Fprint(w, s, " ")
}
} // a channel (just for the fun of it)
type Chan chan int func ChanCreate() Chan {
c := make(Chan)
go func(c Chan) {
for x := ; ; x++ {
c <- x
}
}(c)
return c
} func (ch Chan) ServeHTTP(w http.ResponseWriter, req *http.Request) {
io.WriteString(w, fmt.Sprintf("channel send #%d\n", <-ch))
} // exec a program, redirecting output
func DateServer(rw http.ResponseWriter, req *http.Request) {
rw.Header().Set("Content-Type", "text/plain; charset=utf-8") date, err := exec.Command("/bin/date").Output()
if err != nil {
http.Error(rw, err.Error(), )
return
}
rw.Write(date)
} func Logger(w http.ResponseWriter, req *http.Request) {
log.Print(req.URL)
http.Error(w, "oops", )
} var webroot = flag.String("root", os.Getenv("HOME"), "web root directory") func main() {
flag.Parse() // The counter is published as a variable directly.
ctr := new(Counter)
expvar.Publish("counter", ctr)
http.Handle("/counter", ctr)
http.Handle("/", http.HandlerFunc(Logger))
http.Handle("/go/", http.StripPrefix("/go/", http.FileServer(http.Dir(*webroot))))
http.Handle("/chan", ChanCreate())
http.HandleFunc("/flags", FlagServer)
http.HandleFunc("/args", ArgServer)
http.HandleFunc("/go/hello", HelloServer)
http.HandleFunc("/date", DateServer)
err := http.ListenAndServe(":12345", nil)
if err != nil {
log.Panicln("ListenAndServe:", err)
}
}
curl http://localhost:12345/counter
curl http://localhost:12345/
curl http://localhost:12345/go
curl http://localhost:12345/chan
curl http://localhost:12345/flags
curl http://localhost:12345/args
curl http://localhost:12345/go/hello
curl http://localhost:12345/date
curl http://localhost:12345/xx
Go语言实现简单的一个静态WEB服务器的更多相关文章
- 做的简单的一个静态web服务器,遇到个bug, 提示osError,这点一不小心就错了,特地记下来,加深记忆,socket须先绑定,再listen,如果是先listen再绑定,系统会自动分配一个端口,而程序绑定不了
代码改正之前,先执行了listen,到了bind就报错:此程序只需将listen和改到bind后面即可 from socket import *from multiprocessing import ...
- 用HTTP核心模块配置一个静态Web服务器
静态Web服务器的主要功能由ngx_http_core_module模块(HTTP框架的主要成员)实现与core模块类似,可以根据相关模块(如ngx_http_gzip_filter_module.n ...
- Fenix – 基于 Node.js 的桌面静态 Web 服务器
Fenix 是一个提供给开发人员使用的简单的桌面静态 Web 服务器,基于 Node.js 开发.您可以同时在上面运行任意数量的项目,特别适合前端开发人员使用. 您可以通过免费的 Node.js 控制 ...
- 04-HTTP协议和静态Web服务器
一.HTTP协议(HyperText Transfer Protocol) 超文本传输协议,超文本是超级文本的缩写,是指超越文本限制或者超链接,比如:图片.音乐.视频.超链接等等都属于超文本. ...
- node 创建静态web服务器(上)
声明:本文仅用来做学习记录. 本文将使用node创建一个简单的静态web服务器. 准备工作: 首先,准备好一个类似图片中这样的页面 第一步: 创建 http 服务: const http = requ ...
- Harp – 内置常用预处理器的静态 Web 服务器
Harp 是一个基于 Node.js 平台的静态 Web 服务器,内置流行的预处理器,支持把 Jade, Markdown, EJS, Less, Stylus, Sass, and CoffeeSc ...
- 超简易静态Web服务器
使用 HttpListener 写的一个超简易静态Web服务器 开发环境:VS2010 + .NET2.0 http://files.cnblogs.com/zjfree/EasyIIS.rar
- 深入理解Tornado——一个异步web服务器
本人的第一次翻译,转载请注明出处:http://www.cnblogs.com/yiwenshengmei/archive/2011/06/08/understanding_tornado.html原 ...
- python网络-静态Web服务器案例(29)
一.静态Web服务器案例代码static_web_server.py # coding:utf-8 # 导入socket模块 import socket # 导入正则表达式模块 import re # ...
随机推荐
- 欧拉回路(hdu3018)
刚学图论不久,看着别人的博客慢慢学了一点基础的,感觉还是有点力不从心,感觉图论的题好多长得都很像,什么太监算法(Tarjan),Kosaraju,当然最基础的还是并查集...好了继续介绍这道题.... ...
- 《简明python教程》笔记二
面向对象的编程: 类和对象是面向对象编程的两个主要方面.类创建一个新类型,而对象是这个类的实例.对象可以使用普通的属于对象的变量存储数据.属于一个对象或类的变量被称为域.对象也可以使用属于类的函数来具 ...
- Less2css error 终极解决方案(转载)
用到less时遇到的问题 ,然后复制过来的 使用sublime Text3 的时候,安装less2Css后,和很多人一样以为大功告成,开始要运行编译less文件,结果开始发现 于是乎开始搜索问题和解决 ...
- [git] git代理及常用命令,远程桌面代理
1.代理 公司只能内网,上外网只能用代理,坑货! 2. 更新代码命令 1)下载代码:git clone ------------ 2) 指定目录: cd 文件名 3)git add ...
- 动态代理proxy与CGLib的区别
什么是代理? 静态代理与动态代理 静态代理实例 JDK动态代理实例 CGLib 简介 CGLib 与JDK动态代理的区别 代理模式是Java中常见的一种模式,英文名字叫走Proxy或者Surrogat ...
- POJ Challenge消失之物
Description ftiasch 有 N 个物品, 体积分别是 W1, W2, ..., WN. 由于她的疏忽, 第 i 个物品丢失了. "要使用剩下的 N - 1 物品装满容积为 x ...
- cfDNA(circulating cell free DNA)全基因组测序
参考资料: [cfDNA专题]cell-free DNA在非肿瘤疾病中的临床价值(好) ctDNA, cfDNA和CTCs有什么区别吗? cfDNA你懂多少? 新发现 | 基因是否表达,做个cfDNA ...
- OneProxy自动剔除延迟节点
在多种情况下,MySQL主从节点之间可能存在延迟.比如,主库的写入能力强于从库的写入能力.从库单线程复制.从库复制出错导致相关进程停止.为了保证数据的时效性,OneProxy提供了复制时效性检查,用于 ...
- Configure Apache Virtual Hosts - CentOS 7
Difficulty: 2Time: 15 minutes Want to host websites on your server? Using Apache? Great. This articl ...
- MySQL学习记录--操作时间数据
1.返回日期的时间函数 date_add() : 可以为指定日期增加/减少任意一段时间间隔.下面举例将当前日期增加一个月和减少一个月 mysql month) as add_one_month; +- ...