go http.Handler

时间:2024-01-21 20:32:21

http1

package main

import (
"log"
"net/http"
"fmt"
) func main() {
db:=database{"shoes":,"socks":}
log.Fatal(http.ListenAndServe("localhost:5000",db))
}
type dollars float32 func (d dollars) String() string {
return fmt.Sprintf("$%.2f",d)
}
type database map[string]dollars func (db database) ServeHTTP(w http.ResponseWriter, req *http.Request) {
for item,price:=range db{
fmt.Fprintf(w,"%s: %s\n",item,price)
}
}

打开浏览器:http://localhost:5000/

go http.Handler

http2

package main

import (
"fmt"
"net/http"
"log"
) func main() {
db:=database{"shoes":,"socks":}
mux:=http.NewServeMux()
mux.Handle("/list",http.HandlerFunc(db.list))
mux.Handle("/price",http.HandlerFunc(db.price))
log.Fatal(http.ListenAndServe("localhost:5000",mux))
}
type database map[string]dollars
type dollars float32 func (d dollars) String() string {
return fmt.Sprintf("$%.2f",d)
}
func (db database) list(w http.ResponseWriter, req *http.Request) {
for item,price:=range db{
fmt.Fprintf(w,"%s: %s\n",item,price)
}
}
func (db database) price(w http.ResponseWriter,req *http.Request) {
item:=req.URL.Query().Get("item")
price,ok:=db[item]
if !ok{
w.WriteHeader(http.StatusNotFound)
fmt.Fprintf(w,"no such item: %q\n",item)
return
}
fmt.Fprintf(w,"%s\n",price)
}

打开浏览器:http://localhost:5000/price?item=socks

go http.Handler

clock1

package main

import (
"net"
"io"
"time"
"log"
) func main() {
listener,err:=net.Listen("tcp","localhost:8000")
if err!=nil{
log.Fatal(err)
}
for{
conn,err:=listener.Accept()
if err!=nil{
log.Print(err)
continue
}
handleConn(conn)
}
} func handleConn(c net.Conn) {
defer c.Close()
for{
_,err:=io.WriteString(c,time.Now().Format("15:04:05\r\n"))
if err!=nil{
return
}
time.Sleep(*time.Second)
}
}

运行clock1,打开cmd,使用telnet localhost 8000 进行连接

go http.Handler

或者使用下面的程序

netcat1

package main

import (
"io"
"log"
"net"
"os"
) func main() {
conn,err:=net.Dial("tcp","localhost:8000")
if err!=nil{
log.Fatal(err)
}
defer conn.Close()
mustCopy(os.Stdout,conn)
} func mustCopy(dst io.Writer, src io.Reader) {
if _,err:=io.Copy(dst,src);err!=nil{
log.Fatal(err)
}
}

为了让服务器支持并发,只需要在handleConn上添加一个go

clock2

    for{
conn,err:=listener.Accept()
if err!=nil{
log.Print(err)
continue
}
go handleConn2(conn)
}