Golang http ABC

//html 文件參見
http://www.ieyebrain.com:8080/pts/src/master/

package main

import (
	"flag"
	"net/http"
	"io"
	"strings"
	"strconv"
)

type ClientInfo struct {
	id int
	ip string
	name string
}


var (
	addr = flag.String("addr", ":9191", "pts master address")
	clients = make(map[int] ClientInfo)
	sn = 0
	
)

type Web struct {
	w http.ResponseWriter
	req *http.Request 
}


func  newWeb(w http.ResponseWriter, req *http.Request) *Web {
	return &Web{w:w,req:req}
}

func (p *Web) getClientIp() string {
	r := p.req
    	ip := r.Header.Get("X-Real-IP")
    	if ip == "" {
    		ip = strings.Split(r.RemoteAddr, ":")[0]
    	}
    	if ip == "[" {
    		ip = "localhost"
    	}
    	return ip
}

func (p *Web) beginTag(tag string) {
	io.WriteString(p.w, "<" + tag  + ">")
}

func (p *Web) endTag(tag string) {
	io.WriteString(p.w, "</" + tag + ">")
}

func (p *Web) tagVal(tag string, val string) {
	io.WriteString(p.w, "<" + tag + ">" +  val + "</" + tag +  ">")
}

func (p *Web) write(val string) {
	io.WriteString(p.w, val)
}

func (p *Web) htmlTmpl(title string, body string) {
	p.beginTag("html")
	p.beginTag("head")
	p.tagVal("title", title)
	p.endTag("head")
	p.write(body)
	p.endTag("body")
	p.endTag("html")
}




func listHandler(w http.ResponseWriter, req *http.Request) {
	web := newWeb(w,req)
	web.beginTag("html")
	web.beginTag("head")
	web.tagVal("title", "PTS Master")
	web.endTag("head")
	
	web.beginTag("body")	
	web.beginTag("ul")
	for _,v := range clients {
		web.beginTag("li")
		web.write(strconv.Itoa(v.id))
		web.write(" : ")
		web.write(v.ip)
		web.endTag("li")
	}

	web.write(`<hr>`);
	web.write(`<a href="index.html">home</a>`);
	web.endTag("ul")
	web.endTag("body")
	web.endTag("html")
}

func loginHandler(w http.ResponseWriter, req *http.Request) {
	web := newWeb(w,req)

	req.ParseForm()
	id := sn //req.Form["id"]
	//name := req.Form["name"]
	ip := web.getClientIp()
	
	clients[id] = ClientInfo {
			id:id,
			name:ip,
			ip:ip}
	sn++

	web.htmlTmpl("LoginOK",`<a href="list">loginRecord</a>`)
	
}

func main() {
	flag.Parse()
	fileSvr := http.FileServer(http.Dir("html"))
	http.Handle("/",fileSvr) 
	http.HandleFunc("/list", listHandler)
	http.HandleFunc("/login", loginHandler)
	
	err := http.ListenAndServe(*addr, nil)
	panic(err)

}
相關文章
相關標籤/搜索