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. css属性的选择对动画性能的影响

    现在手机的占比越来越高,各种酷炫页面层出不穷,这些特效都离不开css动画.说到css动画,主流的情况也就无非这两大类:位移和形变.而我们在写一个动画特效的过程中,如何去提升它的性能呢?当然首先我们需要 ...

  2. 通用访问 - 用“反射”来设计通用的通信协议,以及配套的SDK、工具

    1. 效果演示 2. 通信协议 功能介绍 特点 TCP协议 WebApi协议 3. SDK与工具 4. 应用示例 迷你网管 通用GIS 系统管理 5. 设计初衷与演化   1. 效果演示     服务 ...

  3. iOS 消息推送报错NSCocoaErrorDomain Code=3000

    转自: http://www.cnblogs.com/zxykit/p/5207498.html Xcode7推送报错.Error Domain=NSCocoaErrorDomain Code=300 ...

  4. Java多线程同步 synchronized 关键字的使用

    代表这个方法加锁,相当于不管哪一个线程A每次运行到这个方法时,都要检查有没有其它正在用这个方法的线程B(或者C D等),有的话要等正在使用这个方法的线程B(或者C D)运行完这个方法后再运行此线程A, ...

  5. windows下如何安装和启动MySQL

    1.下载,解压到自己喜欢的目录 2.配置环境变量.MYSQL_HOME,值为mysql的根目录:在path中添加%MYSQL_HOME%/bin目录. 3.向windows注册mysql服务.必须用管 ...

  6. position之fixed固定定位、absolute绝对定位和relative相对定位

    什么是层模型? 什么是层布局模型?层布局模型就像是图像软件PhotoShop中非常流行的图层编辑功能一样,每个图层能够精确定位操作,但在网页设计领域,由于网页大小的活动性,层布局没能受到热捧.但是在网 ...

  7. java: Thread 和 runnable线程类

    java: Thread 和 runnable线程类 Java有2种实现线程的方法:Thread类,Runnable接口.(其实Thread本身就是Runnable的子类) Thread类,默认有ru ...

  8. SQL SERVER与SSIS 数据类型对应关系

  9. Libpci库的调用

    这几天发现在Redhat AS6.5 X86_64下用outl(index, 0xcf8)和inl(0xcfc)下读取PCIe配置空间是系统有时性的会hang, 于是去寻找解决方案,首先想到的是用/d ...

  10. maven + eclipse + tomcat热部署

    环境:eclipse  + tomcat  + maven + m2eclipse 解决这种问题有两种方案(方案二更好用,不想看方案一的人可以直接绕过). 方案一: 第一种方案摘自http://blo ...