Golang http ABC

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
//html 檔案參見http://www.ieyebrain.com:8080/pts/src/master/package mainimport ("flag""net/http""io""strings""strconv")type ClientInfo struct {id intip stringname string}var (addr = flag.String("addr", ":9191", "pts master address")clients = make(map[int] ClientInfo)sn = 0)type Web struct {w http.ResponseWriterreq *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)}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.