golang学习笔记

前端之家收集整理的这篇文章主要介绍了golang学习笔记前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

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

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

  1. //根据请求中Accept-Encoding 编码方式,如果支持gzip编码,就将返回的数据进行gzip压缩,使用compress/gzip包,执行压缩后需要Close,所有要有Close接口
  2. type CloseableResponseWriter interface {
  3. http.ResponseWriter
  4. Close()
  5. }
  6.  
  7. type gzipResponseWriter struct {
  8. http.ResponseWriter
  9. *gzip.Writer
  10. }
  11.  
  12. func (gw gzipResponseWriter) Write(data []byte) (int,error) {
  13. return gw.Write(data)
  14. }
  15.  
  16. func (gw gzipResponseWriter) Close() {
  17. gw.Writer.Close()
  18. }
  19.  
  20. func (gw gzipResponseWriter) Header() http.Header {
  21. return gw.ResponseWriter.Header()
  22. }
  23.  
  24. //对于不支持gzip压缩的,也封装为还有方法Close()的类型
  25. type closeableResponseWriter struct {
  26. http.ResponseWriter
  27. }
  28.  
  29. func (cw closeableResponseWriter) Close() {
  30. return
  31. }
  32.  
  33. func GetResonseWriter(w http.ResponseWriter,req *http.Request) CloseableResponseWriter {
  34. if strings.Contains(req.Header.Get("Accept-Encoding"),"gzip") {
  35. w.Header().Set("Content-Encoding","gzip")
  36. gRw := gzipResponseWriter{
  37. ResponseWriter: w,Writer: gzip.NewWriter(w),}
  38. return gRw
  39. } else {
  40. return closeableResponseWriter{ResponseWriter: w}
  41. }
  42. }
  43.  
  44. func gzipHandler(w http.ResponseWriter,req *http.Request) {
  45. w.Header().Add("Content Tpye","text/html")
  46. responseWrite := GetResonseWriter(w,req)
  47. defer responseWrite.Close()
  48.  
  49. }

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

  1. type Poem []string
  2.  
  3. //实现String()接口,就可以在fmt.Printf("%s")
  4. func (p Poem) String() string {
  5. re := ""
  6. for _,s := range p {
  7. re = re + s
  8. }
  9. return re
  10. }

fmt.Printf %q

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

返回

  1. "haha \n"

interface{}类型推断

  1. func wahtIsThis(i interface{}) {
  2. switch i.(type) {
  3. case string:
  4. fmt.Printf("this is string %s\n",i.(string)) //注意这里要显示转换
  5. case uint32:
  6. fmt.Printf("this is uint32 %d\n",i.(uint32))//注意这里要显示转换
  7. default:
  8. fmt.Printf("Do not konw\n")
  9. }
  10.  
  11. }
  12.  
  13. func wahtIsThisV2(i interface{}) {
  14. switch v := i.(type) {
  15. case string:
  16. fmt.Printf("this is string %s\n",v) //注意这里不需要转换
  17. case uint32:
  18. fmt.Printf("this is uint32 %d\n",v) //注意这里不需要转换
  19. default:
  20. fmt.Printf("Do not konw\n")
  21. }
  22.  
  23. }

猜你在找的Go相关文章