chenshenhai / blog

个人博客,没事写写玩玩~~~
146 stars 21 forks source link

go语言简单web服务 #18

Open chenshenhai opened 7 years ago

chenshenhai commented 7 years ago

文件目录

.
├── server.go
├── static
│   ├── css
│   │   └── style.css
│   └── js
│       └── index.js
└── template
    └── index.html

server.go 服务

package main

import (
    "net/http"
    "html/template"
    "log"
)

// 渲染模板
func render( writer http.ResponseWriter,  tplFile string, ctx map[string] string) {
    tpl, err := template.ParseFiles( tplFile )
    if err != nil {
        http.Error( writer, err.Error(), http.StatusInternalServerError )
        return
    }
    tpl.Execute( writer, ctx )
}

// 主页操作
func indexHandler( writer http.ResponseWriter, req *http.Request ) {
    context := make(map[string]string)
    context["title"] = "index page"
    context["info"] = "this is a go web"
    render( writer, "template/index.html", context )
    return
}

// main函数
func main() {
    // 主页
    http.HandleFunc("/", indexHandler)

    // 加载静态资源
    http.Handle("/static/js/", http.FileServer(http.Dir("./")))
    http.Handle("/static/css/", http.FileServer(http.Dir("./")))

    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        log.Fatal("ListenAndServe:", err.Error())
    }
}

go语言模板

<html>
    <head>
        <title>{{.title}}</title> 
        <link type="text/css" rel="stylesheet" href="/static/css/style.css" />
    </head>
    <body>
        <div class="box">
            <p>{{.info}}</p>
        </div>
        <script src="/static/js/index.js"></script>
    </body>
</html>

执行go语言web服务

go run server.go

访问 http://localhost:8080

go-simple-web-server