当前位置: 移动技术网 > IT编程>脚本编程>Go语言 > 浅谈go语言renderer包代码分析

浅谈go语言renderer包代码分析

2018年05月11日  | 移动技术网IT编程  | 我要评论

renderer是go语言的一个简单的、轻量的、快速响应的呈现包,它可以支持json、jsonp、xml、hyaml、html、file等类型的响应。在开发web应用或restful api的时候,这个包是非常方便的toolkit。

本文绕开如何使用它,深入到代码实现中研究它,同时也尝尝go语言包的开发套路。

go包基础介绍

代码结构

package pkgname

import (
  "fmt"
  ...
)
const (
  const1 typex = xx
  ...
)

var (
  var1 typex = xxx
  ...
)

func fn1() {
}

在go语言中包名和目录名保持一致,同一包内可共享命名空间。

  1. 包文件开头除了注释外,第一行,必须是package pkgname, 声明包的名称。
  2. 在包声明之后,可以import标准库中的包和其他外部包。
  3. 然后可以定义包常量、包变量(暴露变量和非暴露变量,以首字母大小写来区分实现)。
  4. 然后定义自定义类型、函数或方法。

import语句

import可以引入标准库的包,也可以引入外部包。go语言中一旦引入某个包,必须在程序中使用到这个包的命名空间,否则编译报错会告诉你引入了某个包,但代码中未曾使用。

当然你也会有疑问,我如果需要引入包,但又不想使用怎么办。这个go语言有一个特殊的符号"_", 放在引入包名前面,就可以防止编译报错。为什么会有这种考虑呢? 因为有时候,我们只是希望引入一个包,然后执行这个包的一些初始化设置。然后在代码中暂时不使用该包的任何方法和变量。

import (
  _ "github.com/xxxxx/pkgname"
)

上面语句会引入pkgname命名空间,但是暂时不在代码中使用这个命名空间。这样引入之后,会在pkgname包中寻找init()函数,然后在main()函数执行之前先执行它们,这点对于需要使用包之前做初始化非常有用。

暴露与非暴露的实现

我们在其他编程语言中,都接触过private, protected, public之类的修饰符。 但是在go语言中完全没有这些,但是go语言还是可以某些东西从包中暴露出去,而某些东西不暴露出去,它用的原则很简单的,就是标识符如果以小写字母开头的,包外不可见; 而如果是标识符以大写字符开头的,包外可见,可访问。

对于暴露变量和函数(方法)非常直观简单,但是如果是暴露的结构体,情况稍微复杂一点。 不过本质上也是差不多, 结构体外部如果小写字母开头,内部属性大写字母开头。 则外部包直接不访问,但如果通过函数或方法返回这个外部类型,那么可以通过:=得到这个外部类型,从而可以访问其内部属性。举例如下:

// package pkgname
package pkgname

type admin struct {
  name string
  email string
}

func admin() *admin {
  return &admin{
    name: "admin",
    email: "admin@email.com",
  }
}

那么我们在外部包中,可以直接通过下面代码访问admin结构体内部的属性:

admin := pkgname.admin()

fmt.println(admin.name, admin.email)

当然这种情况下,需要你事先知道admin的结构以及包含的属性名。

内置类型和自定义类型

go语言包含了几种简单的内置类型:整数、布尔值、数组、字符串、分片、映射等。除了内置类型,go语言还支持方便的自定义类型。

自定义类型有两种:

  1. 自定义结构体类型: type mytype struct {}这种形式定义,这种类似c语言中的结构体定义。
  2. 命名类型: type myint int。这种方式通过将内置类型或自定义类型命名为新的类型的方式来实现。 需要注意myint和int是不同的类型,它们之间不能直接互相赋值。

函数和方法

go语言的函数和方法都是使用func关键词声明的,方法和函数的唯一区别在于,方法需要绑定目标类型; 而函数则无需绑定。

type mytype struct {
}

// 这是函数
func dosomething() {

}

// 这是方法
func (mt mytype) mymethod() {
}

// 或者另外一种类型的方法
func (mt *mytype) mymethod2() {
}

对于方法来说,需要绑定一个receiver, 我称之为接收者。 接收者有两种类型:

  1. 值类型的接收者
  2. 指针类型的接收者

关于接收者和接口部分,有很多需要延伸的,后续有时间整理补充出来。

接口

代码分析

常量部分

代码分析部分,我们先跳过import部分, 直接进入到常量的声明部分。

const (
  // contenttype represents content type
  contenttype string = "content-type"
  // contentjson represents content type application/json
  contentjson string = "application/json"
  // contentjsonp represents content type application/javascript
  contentjsonp string = "application/javascript"
  // contentxml represents content type application/xml
  contentxml string = "application/xml"
  // contentyaml represents content type application/x-yaml
  contentyaml string = "application/x-yaml"
  // contenthtml represents content type text/html
  contenthtml string = "text/html"
  // contenttext represents content type text/plain
  contenttext string = "text/plain"
  // contentbinary represents content type application/octet-stream
  contentbinary string = "application/octet-stream"

  // contentdisposition describes contentdisposition
  contentdisposition string = "content-disposition"
  // contentdispositioninline describes content disposition type
  contentdispositioninline string = "inline"
  // contentdispositionattachment describes content disposition type
  contentdispositionattachment string = "attachment"

  defaultcharset      string = "utf-8"
  defaultjsonprefix     string = ""
  defaultxmlprefix     string = `<?xml version="1.0" encoding="iso-8859-1" ?>\n`
  defaulttemplateext    string = "tpl"
  defaultlayoutext     string = "lout"
  defaulttemplateleftdelim string = "{{"
  defaulttemplaterightdelim string = "}}"
)

以上常量声明了内容类型常量以及本包支持的各种内容类型mime值。以及各种具体内容类型相关的常量,比如字符编码方式、jsonp前缀、xml前缀,模版左右分割符等等一些常量。

类型声明部分

这部分声明了如下类型:

  1. m: 映射类型,描述代表用于发送的响应数据便捷类型。
  2. options: 描述选项类型。
  3. render: 用于描述renderer类型。
type (
  // m describes handy type that represents data to send as response
  m map[string]interface{}

  // options describes an option type
  options struct {
    // charset represents the response charset; default: utf-8
    charset string
    // contentjson represents the content-type for json
    contentjson string
    // contentjsonp represents the content-type for jsonp
    contentjsonp string
    // contentxml represents the content-type for xml
    contentxml string
    // contentyaml represents the content-type for yaml
    contentyaml string
    // contenthtml represents the content-type for html
    contenthtml string
    // contenttext represents the content-type for text
    contenttext string
    // contentbinary represents the content-type for octet-stream
    contentbinary string

    // unescapehtml set unescapehtml for json; default false
    unescapehtml bool
    // disablecharset set disablecharset in response content-type
    disablecharset bool
    // debug set the debug mode. if debug is true then every time "view" call parse the templates
    debug bool
    // jsonindent set json indent in response; default false
    jsonindent bool
    // xmlindent set xml indent in response; default false
    xmlindent bool

    // jsonprefix set prefix in json response
    jsonprefix string
    // xmlprefix set prefix in xml response
    xmlprefix string

    // templatedir set the template directory
    templatedir string
    // templateextension set the template extension
    templateextension string
    // leftdelim set template left delimiter default is {{
    leftdelim string
    // rightdelim set template right delimiter default is }}
    rightdelim string
    // layoutextension set the layout extension
    layoutextension string
    // funcmap contain function map for template
    funcmap []template.funcmap
    // parseglobpattern contain parse glob pattern
    parseglobpattern string
  }

  // render describes a renderer type
  render struct {
    opts     options
    templates   map[string]*template.template
    globtemplates *template.template
    headers    map[string]string
  }
)

new函数

// new return a new instance of a pointer to render
func new(opts ...options) *render {
  var opt options
  if opts != nil {
    opt = opts[0]
  }

  r := &render{
    opts:   opt,
    templates: make(map[string]*template.template),
  }

  // build options for the render instance
  r.buildoptions()

  // if templatedir is not empty then call the parsetemplates
  if r.opts.templatedir != "" {
    r.parsetemplates()
  }

  // parseglobpattern is not empty then parse template with pattern
  if r.opts.parseglobpattern != "" {
    r.parseglob()
  }

  return r
}

用于创建render类型的函数。它接受options类型的参数,返回一个render类型。

我们一般通常不传入options类型变量调用renderer.new()来创建一个render类型。

  var opt options
  if opts != nil {
    opt = opts[0]
  }

  r := &render{
    opts:   opt,
    templates: make(map[string]*template.template),
  }

上面这段代码实际上就是初始化了一个render类型的r变量。opts为nil, templates为map类型,这里被初始化。

接下来调用r.buildoptions()方法。

buildoptions方法

func (r *render) buildoptions() {
  if r.opts.charset == "" { // 没有指定编码方式,使用默认的编码方式utf-8
    r.opts.charset = defaultcharset
  }

  if r.opts.jsonprefix == "" { // 没有指定json前缀,使用默认的
    r.opts.jsonprefix = defaultjsonprefix
  }

  if r.opts.xmlprefix == "" { // 没有指定xml前缀,使用默认xml前缀
    r.opts.xmlprefix = defaultxmlprefix
  }

  if r.opts.templateextension == "" { // 模版扩展名设置
    r.opts.templateextension = "." + defaulttemplateext
  } else {
    r.opts.templateextension = "." + r.opts.templateextension
  }

  if r.opts.layoutextension == "" { // 布局扩展名设置
    r.opts.layoutextension = "." + defaultlayoutext
  } else {
    r.opts.layoutextension = "." + r.opts.layoutextension
  }

  if r.opts.leftdelim == "" { // 模版变量左分割符设置
    r.opts.leftdelim = defaulttemplateleftdelim
  }

  if r.opts.rightdelim == "" { // 模版变量右分割符设置
    r.opts.rightdelim = defaulttemplaterightdelim
  }

  // 设置内容类型属性常量
  r.opts.contentjson = contentjson 
  r.opts.contentjsonp = contentjsonp
  r.opts.contentxml = contentxml
  r.opts.contentyaml = contentyaml
  r.opts.contenthtml = contenthtml
  r.opts.contenttext = contenttext
  r.opts.contentbinary = contentbinary

  // 如果没有禁用编码集,那么就将内容类型后面添加字符集属性。
  if !r.opts.disablecharset {
    r.enablecharset()
  }
}

该方法构建render的opts属性,并绑定默认的值。

我们看了new函数,得到了一个render类型,接下来就是呈现具体类型的内容。我们以json为例,看看它怎么实现的。

json方法

如果没有renderer包,我们想要用go语言发送json数据响应,我们的实现代码大致如下:

func dosomething(w http.responsewriter, ...) {
  // json from a variable v
  jdata, err := json.marshal(v)
  if err != nil {
    panic(err)
    return
  }
  w.header().set("content-type", "application/json")
  w.writeheader(200)
  w.write(jdata)
}

原理很简单,首先从变量中解析出json, 然后发送content-type为application/json, 然后发送状态码, 最后将json序列发送出去。

那么我们再详细看看renderer中的json方法的实现:

func (r *render) json(w http.responsewriter, status int, v interface{}) error {
  w.header().set(contenttype, r.opts.contentjson)
  w.writeheader(status)

  bs, err := r.json(v)
  if err != nil {
    return err
  }
  if r.opts.jsonprefix != "" {
    w.write([]byte(r.opts.jsonprefix))
  }
  _, err = w.write(bs)
  return err
}

大致看上去,和我们不使用renderer包的实现基本一样。指定content-type, 发送http状态码,然后看json前缀是否设置,如果设置,前缀也发送到字节流中。 最后就是发送json字节流。

唯一区别在于,我们使用encoding/json包的marshal方法来将给定的值转换成二进制序列,而renderer对这个方法进行了包装:

func (r *render) json(v interface{}) ([]byte, error) {
  var bs []byte
  var err error
  if r.opts.jsonindent {
    bs, err = json.marshalindent(v, "", " ")
  } else {
    bs, err = json.marshal(v)
  }
  if err != nil {
    return bs, err
  }
  if r.opts.unescapehtml {
    bs = bytes.replace(bs, []byte("\\u003c"), []byte("<"), -1)
    bs = bytes.replace(bs, []byte("\\u003e"), []byte(">"), -1)
    bs = bytes.replace(bs, []byte("\\u0026"), []byte("&"), -1)
  }
  return bs, nil
}

如果有设置jsonindent, 即json缩进,那么使用json.marshalindent来将变量转换为json字节流。 这个方法其实就是将json格式化,使得结果看起来更好看。

另外这个方法还会根据配置,进行html实体的转义。

因此总体来说原理和开头的代码基本一样。只不过多了一些额外的修饰修补。

jsonp方法

我们理解了json方法,理解起jsonp就更加简单了。

jsonp全称为json with padding, 用于解决ajax跨域问题的一种方案。

它的原理非常简单:

// 客户端代码
var dosomething = function(data) {
  // do something with data
}

var url = "server.jsonp?callback=dosomething";
 // 创建 <script> 标签,设置其 src 属性
 var script = document.createelement('script');
 script.setattribute('src', url);

 // 把 <script> 标签加入 <body> 尾部,此时调用开始。
 document.getelementsbytagname('body')[0].appendchild(script);
上面server.jsonp是一个后台脚本,访问后立即返回它的输出内容, 这也就是renderer的jsonp要响应的内容。

func (r *render) jsonp(w http.responsewriter, status int, callback string, v interface{}) error {
  w.header().set(contenttype, r.opts.contentjsonp)
  w.writeheader(status)

  bs, err := r.json(v)
  if err != nil {
    return err
  }

  if callback == "" {
    return errors.new("renderer: callback can not bet empty")
  }

  w.write([]byte(callback + "("))
  _, err = w.write(bs)
  w.write([]byte(");"))

  return err
}

  1. 设置content-type为application/javascript, 非常关键的一点。 想一想html中嵌入的js文件的mime类型是不是也是这个值?
  2. 然后同样的设置响应状态码, 这点没有什么特殊的。
  3. 将值转换为json字节序列。这个json字节序列还没有向响应写入进去。
  4. 这个时候我们检查callback是否存在,不存在报错出去。因为是jsonp, 必须要有callback, 这个callback是请求参数传入的。
  5. 然后用"callbak("和")"将json字节序列包围起来,一起输出到响应流中。这样jsonp响应就产生了。

那么回过头结合我们开头写的一个前段jsonp代码,我们知道请求了server.jsonp?callback=xxxx之后,一个application/javascript的内容被嵌入到body内。它是js文件。 而其内容将callback替换为传入的dosomething, 我们得到类似的js内容:

dosomething({
  // ....
});

这样服务端产生数据,并调用前端js的方法, 传入这些数据, jsonp就完成了。这样的js一旦加载成功,它和当前访问域名是同源的,不存在跨域问题。 这样就解决了ajax跨域问题。

剩下的其他方法基本都是同样的套路, 这里不再赘述, 有时间的话再重新整理下开头的内容。

本文仅个人学习整理, 如有不对之处, 还望各位不吝指出。

在链接部分,有我自己对go in action英文书籍的翻译, 英文比较差,再者也是初学go语言,翻译不到位, 有兴趣的朋友可以一起翻译此书,或者后续有其他好的技术书籍,一起翻译学习。

引用链接

  1. go in action

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网