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")
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值