加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

golang学习笔记

发布时间:2020-12-16 09:45:44 所属栏目:大数据 来源:网络整理
导读:web开发中支持gzip压缩返回 自定义类型支持fmtPrintfs fmtPrintf q interface类型推断 基于下面两个视频课程的笔记 「课程」使用Go建立Web应用程序(Creating Web Applications with Go) 「教程」Go语言基础 (O’Reilly) 除此之外 【课程】Go编程经典设计模
    • 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("%qn",a)

返回

"haha n"

interface{}类型推断

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

}

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

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读