今天博主研究完东西实在太晚了,大家可以看时间一点多了,今天是代码1,明天是讲解,大家先研究一下
[php]
package main
import (
//"fmt"
"html/template"
"log"
"net/http"
"os"
"time"
)
const (
TEMPLATE_DIR = "./views/"
)
var mux map[string]func(http.ResponseWriter, *http.Request)
func main() {
server := http.Server{
Addr: ":9090",
Handler: &MyHandler{},
ReadTimeout: 6 * time.Second,
}
mux = make(map[string]func(http.ResponseWriter, *http.Request))
mux["/"] = home
mux["/login"] = login
server.ListenAndServe()
}
type MyHandler struct{}
func (*MyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if h, ok := mux[r.URL.String()]; ok {
h(w, r)
return
} else {
defer f.Close()
f, err := os.Open("." + r.URL.String())
if err != nil && os.IsNotExist(err) {
http.NotFound(w, r)
return
} else {
http.ServeFile(w, r, "."+r.URL.String())
}
return
}
}
type index struct {
Title string
}
func login(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
t, err := template.ParseFiles(TEMPLATE_DIR + "login.html")
if err != nil {
log.Fatal(err)
}
index := index{Title: "首页"}
t.Execute(w, index)
}
}
func home(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
t, err := template.ParseFiles(TEMPLATE_DIR + "index.html")
if err != nil {
log.Fatal(err)
}
index := index{Title: "首页"}
t.Execute(w, index)
}
}
[/php]
未经允许,不得转载本站任何文章:微度网络 » golang(go语言)网页制作实例代码1
有疑问加站长微信联系(非本文作者)