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服务器的更多相关文章

  1. 做的简单的一个静态web服务器,遇到个bug, 提示osError,这点一不小心就错了,特地记下来,加深记忆,socket须先绑定,再listen,如果是先listen再绑定,系统会自动分配一个端口,而程序绑定不了

    代码改正之前,先执行了listen,到了bind就报错:此程序只需将listen和改到bind后面即可 from socket import *from multiprocessing import ...

  2. 用HTTP核心模块配置一个静态Web服务器

    静态Web服务器的主要功能由ngx_http_core_module模块(HTTP框架的主要成员)实现与core模块类似,可以根据相关模块(如ngx_http_gzip_filter_module.n ...

  3. Fenix – 基于 Node.js 的桌面静态 Web 服务器

    Fenix 是一个提供给开发人员使用的简单的桌面静态 Web 服务器,基于 Node.js 开发.您可以同时在上面运行任意数量的项目,特别适合前端开发人员使用. 您可以通过免费的 Node.js 控制 ...

  4. 04-HTTP协议和静态Web服务器

    一.HTTP协议(HyperText Transfer Protocol)     超文本传输协议,超文本是超级文本的缩写,是指超越文本限制或者超链接,比如:图片.音乐.视频.超链接等等都属于超文本. ...

  5. node 创建静态web服务器(上)

    声明:本文仅用来做学习记录. 本文将使用node创建一个简单的静态web服务器. 准备工作: 首先,准备好一个类似图片中这样的页面 第一步: 创建 http 服务: const http = requ ...

  6. Harp – 内置常用预处理器的静态 Web 服务器

    Harp 是一个基于 Node.js 平台的静态 Web 服务器,内置流行的预处理器,支持把 Jade, Markdown, EJS, Less, Stylus, Sass, and CoffeeSc ...

  7. 超简易静态Web服务器

    使用 HttpListener 写的一个超简易静态Web服务器 开发环境:VS2010 + .NET2.0 http://files.cnblogs.com/zjfree/EasyIIS.rar

  8. 深入理解Tornado——一个异步web服务器

    本人的第一次翻译,转载请注明出处:http://www.cnblogs.com/yiwenshengmei/archive/2011/06/08/understanding_tornado.html原 ...

  9. python网络-静态Web服务器案例(29)

    一.静态Web服务器案例代码static_web_server.py # coding:utf-8 # 导入socket模块 import socket # 导入正则表达式模块 import re # ...

随机推荐

  1. T-SQL编程 —— 用户自定义函数(内嵌表值函数)

    内嵌表值函数 接上 <T-SQL编程 -- 用户自定义函数(标量函数)> http://www.cnblogs.com/viusuangio/p/6212072.html 内嵌表值函数可以 ...

  2. css实现div的高度填满剩余空间

    css实现div的高度填满剩余空间 .top{ width: 100%; height: 70px;} .bottom{background-color: #cc85d9;width: 100%;po ...

  3. Lua热更系统

    1.介绍 使用脚本开发游戏业务逻辑其中一个好处就是代码可线上热更,不停机修复bug.而热更代码的写法与需要被热更的文件的代码又有着密切的关系,本文介绍一种热更方法. 2.热更原理 Lua提供一个叫re ...

  4. jquery总结06-动画事件02-上卷下拉动画

    .slideDown() 下拉动画 动画执行之后的操作写在回调函数里 $("ele").slideDown(1000, function() { //等待动画执行1秒后,执行别的动 ...

  5. P​D​F​二​次​开​发​_​i​S​t​y​l​e​P​D​F​表​单​域​的​填​充

    wo讲到PDF表单,我们首先需要认识Adobe定义的PDF表单有哪些.以下是我从网上搜索到的简单介绍: PDF 表单简介 PDF 是可移植文档格式(Portable Document Format)的 ...

  6. 实验二 用C语言表示进程的调度

    实验二 一. 实验目的 通过模拟进程的调度,进一步了解进程的调度的具体过程. 二. 实验内容和要求 1.进程PCB的结构体定义 2.定义队列 3.输入进程序列 4.排序(按到位时间) 5.输出进程运行 ...

  7. jupyter nb + scite 混合搭建成我的最爱IDE

    jupyter nb + scite 混合搭建成我的最爱IDE 自从体验过jupyter notebook之后, 就深深地爱上了你, jupyter. jupyter这个名字也很古怪的. 它应该是ju ...

  8. iBatis框架基本使用

    iBatis框架是Java持久层开发框架,说白了就是前人写了一部分代码(针对数据库操作),我们要做的就是再次开发,拿来框架直接使用. 我们自己开发时,dao层的sql语句都是写死在程序中的,如果查询条 ...

  9. win7 winsxs精简 cmd 脚本之 再次 改进版

    dos时代菜鸟发表于 2012-7-24 http://bbs.wuyou.net/forum.php?mod=viewthread&tid=255200&highlight=win7 ...

  10. try-catch

    try{ // 程序代码 }catch(异常类型1 异常的变量名1){ // 程序代码 }catch(异常类型2 异常的变量名2){ // 程序代码 }catch(异常类型2 异常的变量名2){ // ...