Go语言http服务器

下面的代码在hello world的基础上,使用ioutil库做文件操作也能实现基础的服务了。

package main

import (
    "fmt"
    "net/http"
    "io/ioutil"
)

func handler(w http.ResponseWriter, r *http.Request) {
    contents, err := ioutil.ReadFile(r.URL.Path[1:])
    if err != nil {
        fmt.Fprintf(w, "404")
        return
    }
    fmt.Fprintf(w, "%s!\n", contents)
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}
原文地址:https://www.cnblogs.com/damir/p/2486521.html