Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

go语言简单web服务 #18

Open
chenshenhai opened this issue Mar 24, 2017 · 0 comments
Open

go语言简单web服务 #18

chenshenhai opened this issue Mar 24, 2017 · 0 comments
Labels

Comments

@chenshenhai
Copy link
Owner

chenshenhai commented Mar 24, 2017

文件目录

.
├── 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

@chenshenhai chenshenhai added the go label Mar 24, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant