golang学习笔记

基于下面两个视频课程的笔记
「课程」使用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")
    }

}

相关文章

什么是Go的接口? 接口可以说是一种类型,可以粗略的理解为他...
1、Golang指针 在介绍Golang指针隐式间接引用前,先简单说下...
1、概述 1.1 Protocol buffers定义 Protocol buffe...
判断文件是否存在,需要用到"os"包中的两个函数: os.Stat(...
1、编译环境 OS :Loongnix-Server Linux release 8.3 CPU指...
1、概述 Golang是一种强类型语言,虽然在代码中经常看到i:=1...