go http.Handler

http1

package main

import (
    "log"
    "net/http"
    "fmt"
)

func main() {
    db:=database{"shoes":50,"socks":5}
    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)
    }
}
View Code

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

 

 http2

package main

import (
    "fmt"
    "net/http"
    "log"
)

func main() {
    db:=database{"shoes":50,"socks":5}
    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)
}
View Code

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

 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(1*time.Second)
    }
}
View Code

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

 或者使用下面的程序

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

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

clock2

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

 

转载于:https://www.cnblogs.com/uptothesky/p/8585894.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
引用中提到了http.Handler的ServeHTTP方法。在这个方法中,首先检查handler是否为空,如果为空,则使用默认的处理程序DefaultServeMux来处理请求。这意味着http.Handler是一个接口类型,它定义了ServeHTTP方法,并且可以根据需要被替换为不同的处理程序。在引用的示例代码中,自定义的myHandler类型实现了http.Handler接口,并定义了ServeHTTP方法来处理不同的URL路径。在main函数中,将自定义的myHandler作为参数传递给http.ListenAndServe函数来处理HTTP请求。这样,当有请求到达时,会根据URL路径来选择相应的处理程序。这种方式使得web服务器能够将请求分派给任意的http.Handler,而不需要考虑其具体类型。这也体现了在Go语言中,满足同一个接口的不同类型是可以替换的。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [golang学习之go web 开发http.HandleFunc、http.ListenAndServe与http.Handler](https://blog.csdn.net/weixin_56349119/article/details/126335261)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [Go语言圣经 - 第7章 接口 - 7.7 http.Handler 接口](https://blog.csdn.net/weixin_51487151/article/details/122318673)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值