golang Go中的简单静态文件服务器

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了golang Go中的简单静态文件服务器相关的知识,希望对你有一定的参考价值。

/*
Serve is a very simple static file server in go
Usage:
	-p="8100": port to serve on
	-d=".":    the directory of static files to host

Navigating to http://localhost:8100 will display the index.html or directory
listing file.
*/
package main

import (
	"flag"
	"log"
	"net/http"
)

func main() {
	port := flag.String("p", "8100", "port to serve on")
	directory := flag.String("d", ".", "the directory of static file to host")
	flag.Parse()

	http.Handle("/", http.FileServer(http.Dir(*directory)))

	log.Printf("Serving %s on HTTP port: %s\n", *directory, *port)
	log.Fatal(http.ListenAndServe(":"+*port, nil))
}

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(1)
    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 := 0; ; 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(), 500)
        return
    }
    rw.Write(date)
}

func Logger(w http.ResponseWriter, req *http.Request) {
    log.Print(req.URL)
    http.Error(w, "oops", 404)
}

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

以上是关于golang Go中的简单静态文件服务器的主要内容,如果未能解决你的问题,请参考以下文章

golang golang构建简单的服务器,和静态文件

Golang 的静态编译

golang怎么实现psd

如何在golang 中调用c的静态库或者动态库

Go语言入门

golang 和Python 那个好