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 # ...
随机推荐
- lucene 搜索demo
package com.ljq.utils; import java.io.File; import java.util.ArrayList; import java.util.List; impor ...
- 文件上传(excel服务端解析)
1,html结构 <!-- 引入jQuery和jQuery.form.js插件 --><script type="text/javascript" src=&qu ...
- /boot/grub/device.map【设备映射】
grub-install 安装 GRUB 在第一个硬盘的 MBR: # grub-install '(hd0)' grub-install 会先搜寻设备对应的文件(/boot/grub/device. ...
- freeMarker生成静态页面
项目结构图 footer.ftl des==>${f.des}<br/> <a href="http://www.baidu.com"> 百度 < ...
- OpenCV学习笔记(一)——OpenCV安装
1.无脑安装以下安装文件 cn_visual_studio_2010_ultimate_x86_dvd_532347.iso 2.测试Hello OpenCV 文件→新建→项目 win32应用程序→下 ...
- ubuntu14.04 Hadoop单机开发环境搭建MapReduce项目
Hadoop官网:http://hadoop.apache.org/ 目前最新的版本是Hadoop 3.0.0-alpha1前提:java 1.6 版本以上 首先从官网下载压缩包(hadoop-3.0 ...
- Surface与SurfaceView、SurfaceHolder
什么是Surface? android API的解释是:Handle onto a raw buffer that is being managed by the screen compositor ...
- 打开hibernate文件报警告
在web工程中新建一个,Hibetnate项目,打开配置文件报警高错误,This project is not a MyEclipse Hiberbate Project. Assuming Hibe ...
- spring框架学习(六)AOP
AOP(Aspect-OrientedProgramming)面向方面编程,与OOP完全不同,使用AOP编程系统被分为方面或关注点,而不是OOP中的对象. AOP的引入 在OOP面向对象的使用中,无可 ...
- ActiveReport 同一单元格内图片跟文字按条件显示
ActiveReports支持提供Image控件来显示图片素材,Image控件的值可以为图像的二进制流,图像路径,或url等:而在很多情况下,图片是签名扫描文件,并不会一直有值.如果图片的值为空,则显 ...