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. Java Web之JavaBean

    一.什么是javaBean javaBean是一个遵循特定写法的java类,通常具有如下的特点: 这个java类必须具有一个无参的构造函数. 属性必须私有化. 私有化的属性必须通过public类型的方 ...

  2. 事件委托和JQ事件绑定总结

    事件委托: 比喻:事件委托的事例在现实当中比比皆是.比如,有三个同事预计会在周一收到快递.为签收快递,有两种办法:一是三个人在公司门口等快递:二是委托给前台MM代为签收.现实当中,我们大都采用委托的方 ...

  3. 集​群​t​o​m​c​a​t​+​a​p​a​c​h​e​配​置​文​档

    http://wenku.baidu.com/link?url=M_Lt07e-9KTIHucYgJUCNSxkjWThUuQ2P8axn8q6YmY_yQw7NmijQoDA2wKmi_FQUxwO ...

  4. iframe布局

    代码如下: <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF ...

  5. public protect private. 草稿。

    public protect private. 草稿. #include <iostream> #include <thread> #include <memory> ...

  6. 参考__CSS参考

    库 CsshakeAnimate.css

  7. mybatis mysql 调用视图

    java代码 @RequestMapping(value = "/testView", method = RequestMethod.GET) public @ResponseBo ...

  8. mysql delete 使用别名 语法

    今天删除数据,写了这么条sql语句, DELETE   from  sys_menus s WHERE s.MENU_ID in (86,87,88); 结果报错.. [Err] 1064 - You ...

  9. Software Engineering: 3. Project planning

    recourse: "Software Engineering", Ian Sommerville Keywords for this chapter: planning sche ...

  10. contiki-process结构体

    struct process { struct process *next; #if PROCESS_CONF_NO_PROCESS_NAMES #define PROCESS_NAME_STRING ...