极客兔兔GeeCache Day3

  • http标准库

    • http.ListenAndServe()传入两个参数,第一个参数是服务启动的地址,第二个参数是一个Handler,只要实现了ServeHTTP()方法的对象就是一个Handler

    • http.Handler接口如下

      • type Handler interface {
            ServeHTTP(w ResponseWriter, r *Request)
        }
        
    • 使用ListenAndServe()

      • type server int
        func (h *server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
        	log.Println(r.URL.Path)
        	w.Write([]byte("Hello World!"))
        }
        func main() {
        	var s server
        	http.ListenAndServe("localhost:9999", &s)
        }
        
  • day3主要实现http服务端HTTPPool,接受用户请求,一般来说,大部分网站的API接口都有一个/api作为前缀,这是为了区分不同的服务,因此HTTPPool也有一个字段basePath用来表示前缀,本例中是_geecache,还有一个参数是self用来记录自己的地址

  • strings.SplitN():三个参数,第一个是字符串,第二个是分隔符,第三个是将字符串分割后的最大串数目

    • 若向import相对路径,需要在go.mod文件中加

      • require geecache v0.0.0
        replace geecache => ./geecache
        
  • 代码

    package gee
    
    import (
    	"fmt"
    	"net/http"
    	"strings"
    )
    
    const defaultBasePath = "/_geecache/" // 前缀
    
    type HTTPPool struct {
    	self     string
    	basePath string
    }
    
    func NewHTTPPool(self string) *HTTPPool {
    	return &HTTPPool{
    		self:     self,
    		basePath: defaultBasePath,
    	}
    }
    
    func (p *HTTPPool) Log(format string, v ...interface{}) {
    	fmt.Printf("[Server %s] %s", p.self, fmt.Sprintf(format, v...))
    }
    
    func (p *HTTPPool) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    	if !strings.HasPrefix(r.URL.Path, p.basePath) {
    		panic("没有对应的路径")
    	}
    	p.Log("%s %s", r.Method, r.URL.Path)
    	parts := strings.SplitN(r.URL.Path[len(p.basePath):], "/", 2)
    	if len(parts) != 2 {
    		http.Error(w, "bad request", http.StatusBadRequest)
    		return
    	}
    			
    	groupName := parts[0]
    	key := parts[1]
    	
    	group := GetGroup(groupName)
    	if group == nil {
    		http.Error(w, "对应缓存不存在", http.StatusNotFound)
    		return
    	}
    
    	view, err := group.Get(key)
    	if err != nil {
    		http.Error(w, err.Error(), http.StatusInternalServerError)
    		return
    	}
    
    	w.Header().Set("Content-Type", "application/octet-stream") // 返回的是二进制数据
    	w.Write(view.ByteSlice())
    }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值