龙空技术网

golang HTTP服务 如何加载静态页面

寒笛过霜天 65

前言:

此时朋友们对“golang读取配置文件到静态类”都比较讲究,同学们都需要剖析一些“golang读取配置文件到静态类”的相关知识。那么小编在网摘上网罗了一些有关“golang读取配置文件到静态类””的相关知识,希望你们能喜欢,兄弟们快快来了解一下吧!

main.go

package mainimport (    "fmt"    "io"    "io/ioutil"    "net/http")//加载首页的页面func indexHandler(w http.ResponseWriter, r *http.Request) {    data, err := ioutil.ReadFile("./static/index.html")    if err != nil {    io.WriteString(w, "internel server error")    return    }    io.WriteString(w, string(data))    //w.Write(data)}func main() {    // 静态资源处理    http.Handle("/static/",    http.StripPrefix("/static/",    http.FileServer(http.Dir("./static"))))    // 动态接口路由设置    http.HandleFunc("/index", indexHandler)    // 监听端口    fmt.Println("HTTP服务正在启动, 监听端口:8080...")    err := http.ListenAndServe(":8080", nil)    if err != nil {    		fmt.Printf("Failed to start server, err:%s", err.Error())    }}

static/index.html

<!DOCTYPE html><html><head><meta charset="utf-8"><title></title></head><body><p>这是首页的内容</p></body></html>
D:\work\src>go run main.goHTTP服务正在启动, 监听端口:8080...

访问方式:

标签: #golang读取配置文件到静态类