自学内容网 自学内容网

极客兔兔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())
    }
    

原文地址:https://blog.csdn.net/qq_40052678/article/details/142715005

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!