golang(go语言)网页制作实例代码1

widuu 2013-11-22 Go语言 4,363 1 喜欢 (0)

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

转载请注明来自微度网络,本文标题:《golang(go语言)网页制作实例代码1》

喜欢 0 发布评论
Top