golang实例代码1 今天博主研究完东西实在太晚了,大家可以看时间一点多了,今天是代码1,明天是讲解,大家先研究一下

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)
	}
}

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部