golang学习笔记

    • web开发中支持gzip压缩返回
    • 自定义类型支持fmtPrintfs
    • fmtPrintf q
    • interface类型推断

基于下面两个视频课程的笔记
「课程」使用Go建立Web应用程序(Creating Web Applications with Go)
「教程」Go语言基础 (O’Reilly)

除此之外
【课程】Go编程经典设计模式入门
也不错

web开发中,支持gzip压缩返回


//根据请求中Accept-Encoding 编码方式,如果支持gzip编码,就将返回的数据进行gzip压缩,使用compress/gzip包,执行压缩后需要Close,所有要有Close接口
type CloseableResponseWriter interface {
    http.ResponseWriter
    Close()
}

type gzipResponseWriter struct {
    http.ResponseWriter
    *gzip.Writer
}

func (gw gzipResponseWriter) Write(data []byte) (int, error) {
    return gw.Write(data)
}

func (gw gzipResponseWriter) Close() {
    gw.Writer.Close()
}

func (gw gzipResponseWriter) Header() http.Header {
    return gw.ResponseWriter.Header()
}

//对于不支持gzip压缩的,也封装为还有方法Close()的类型
type closeableResponseWriter struct {
    http.ResponseWriter
}

func (cw closeableResponseWriter) Close() {
    return
}

func GetResonseWriter(w http.ResponseWriter, req *http.Request) CloseableResponseWriter {
    if strings.Contains(req.Header.Get("Accept-Encoding"), "gzip") {
        w.Header().Set("Content-Encoding", "gzip")
        gRw := gzipResponseWriter{
            ResponseWriter: w,
            Writer:         gzip.NewWriter(w),
        }
        return gRw
    } else {
        return closeableResponseWriter{ResponseWriter: w}
    }
}

func gzipHandler(w http.ResponseWriter, req *http.Request) {
    w.Header().Add("Content Tpye", "text/html")
    responseWrite := GetResonseWriter(w, req)
    defer responseWrite.Close()

}

自定义类型支持fmt.Printf(“%s”)

type Poem []string

//实现String()接口,就可以在fmt.Printf("%s")
func (p Poem) String() string {
    re := ""
    for _, s := range p {
        re = re + s
    }
    return re
}

fmt.Printf %q

    a := ("haha \n")
    fmt.Printf("%q\n", a)

返回

"haha \n"

interface{}类型推断


func wahtIsThis(i interface{}) {
    switch i.(type) {
    case string:
        fmt.Printf("this is string %s\n", i.(string)) //注意这里要显示转换
    case uint32:
        fmt.Printf("this is uint32 %d\n", i.(uint32))//注意这里要显示转换
    default:
        fmt.Printf("Do not konw\n")
    }

}

func wahtIsThisV2(i interface{}) {
    switch v := i.(type) {
    case string:
        fmt.Printf("this is string %s\n", v)  //注意这里不需要转换
    case uint32:
        fmt.Printf("this is uint32 %d\n", v) //注意这里不需要转换
    default:
        fmt.Printf("Do not konw\n")
    }

}

你可能感兴趣的:(golang学习笔记)