Beispiel #1
0
func common(t *template.Template) (*template.Template, error) {
	return t.Parse(`
{{ define "header" }}
// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT.

// Package {{ .PackageName }} provides a client for {{ .FullName }}.
package {{ .PackageName }}

import (
  "net/http"
  "time"

  "github.com/awslabs/aws-sdk-go/aws"
  "github.com/awslabs/aws-sdk-go/gen/endpoints"
)

{{ end }}

{{ define "footer" }}
// avoid errors if the packages aren't referenced
var _ time.Time
{{ end }}

`)
}
Beispiel #2
0
func loadTemplateInto(fs vfs.Opener, tpl *template.Template, fName string) (*template.Template, error) {
	src, err := templateSource(fs, fName)
	if err != nil {
		return nil, err
	}
	return tpl.Parse(src)
}
Beispiel #3
0
// formatErrorDescription takes a string in the default text/template
// format and converts it to a string with replacements. The fields come
// from the ErrorDetails struct and vary for each type of error.
func formatErrorDescription(s string, details ErrorDetails) string {

	var tpl *template.Template
	var descrAsBuffer bytes.Buffer
	var err error

	if errorTemplates == nil {
		errorTemplates = template.New("all-errors")
	}

	tpl = errorTemplates.Lookup(s)
	if tpl == nil {
		tpl = errorTemplates.New(s)
		tpl, err = tpl.Parse(s)
		if err != nil {
			return err.Error()
		}
	}

	err = tpl.Execute(&descrAsBuffer, details)
	if err != nil {
		return err.Error()
	}

	return descrAsBuffer.String()
}
Beispiel #4
0
func parseFromFile(t *template.Template, fname string) (*template.Template, error) {
	buf, err := ioutil.ReadFile(fname)
	if err != nil {
		return nil, err
	}
	return t.Parse(string(buf))
}
Beispiel #5
0
func Render(templateName string, options interface{}) (string, error) {
	asset, err := Asset(templateName)
	if err != nil {
		return "", maskAny(err)
	}

	// parse template
	var tmpl *template.Template
	tmpl = template.New(templateName)
	funcMap := template.FuncMap{
		"escape":     escape,
		"quote":      strconv.Quote,
		"yamlPrefix": yamlPrefix,
	}
	tmpl.Funcs(funcMap)
	_, err = tmpl.Parse(string(asset))
	if err != nil {
		return "", maskAny(err)
	}
	// write file to buffer
	tmpl.Funcs(funcMap)
	buffer := &bytes.Buffer{}
	err = tmpl.Execute(buffer, options)
	if err != nil {
		return "", maskAny(err)
	}

	return buffer.String(), nil
}
Beispiel #6
0
func (ctx *TemplateContext) Transform(writer io.Writer, descriptor string) error {
	var t *template.Template

	if b, err := ioutil.ReadFile(descriptor); err != nil {
		return err
	} else {
		var e error
		t = template.New(descriptor).Funcs(Funcs)
		t, e = t.Parse(string(b))
		if e != nil {
			return e
		}
		if matches, err := filepath.Glob("./**/*.tmpl"); err == nil && len(matches) > 0 {
			if t, e = t.ParseFiles(matches...); err != nil {
				return err
			}
		}
	}
	environment := viper.GetString(ENV_NAME)
	m := ctx.mergeAppWithDefault(strings.ToLower(environment))

	if err := t.Execute(writer, m); err != nil {
		return err
	}
	return nil
}
Beispiel #7
0
// Render updates the given destinationPath according to the given template and options.
// Returns true if the file was created or changed, false if nothing has changed.
func Render(templateName, destinationPath string, options interface{}, destinationFileMode os.FileMode) (bool, error) {
	asset, err := Asset(templateName)
	if err != nil {
		return false, maskAny(err)
	}

	// parse template
	var tmpl *template.Template
	tmpl = template.New(templateName)
	funcMap := template.FuncMap{
		"escape": escape,
		"quote":  strconv.Quote,
	}
	tmpl.Funcs(funcMap)
	_, err = tmpl.Parse(string(asset))
	if err != nil {
		return false, maskAny(err)
	}
	// execute template to buffer
	buf := &bytes.Buffer{}
	tmpl.Funcs(funcMap)
	err = tmpl.Execute(buf, options)
	if err != nil {
		return false, maskAny(err)
	}

	// Update file
	changed, err := util.UpdateFile(destinationPath, buf.Bytes(), destinationFileMode)
	return changed, maskAny(err)
}
Beispiel #8
0
func reload(ctx dingo.Context, t *template.Template, v []View) error {
	for _, view := range v {
		if err := reload(ctx, t, view.Extensions()); err != nil {
			return err
		} else if t, err = t.Parse(string(view.Data(ctx))); err != nil {
			log.Printf("Failed to parse extension: (%s)\n%s\n", view.Name(), err)
		}
	}
	return nil
}
Beispiel #9
0
// LoadText loads a template from a possibly inlined VFS as an associated template to the parent
func LoadTextOnto(fs vfs.Opener, parent *txttmpl.Template, tName, fName string) (*txttmpl.Template, error) {
	src, err := templateSource(fs, fName)
	if err != nil {
		return nil, err
	}
	var tpl *txttmpl.Template
	if parent == nil {
		tpl = txttmpl.New(tName)
	} else {
		tpl = parent.New(tName)
	}
	return tpl.Parse(src)
}
Beispiel #10
0
func (m *Migrator) evalMigration(tmpl *template.Template, sql string) (string, error) {
	tmpl, err := tmpl.Parse(sql)
	if err != nil {
		return "", err
	}

	var buf bytes.Buffer
	err = tmpl.Execute(&buf, m.Data)
	if err != nil {
		return "", err
	}

	return buf.String(), nil
}
Beispiel #11
0
func addTemplate(t *template.Template, tname, fname string) (*template.Template, error) {
	buf, err := ioutil.ReadFile(fname)
	if err != nil {
		return nil, err
	}

	var nt *template.Template
	if t != nil {
		nt = t.New(tname)
	} else {
		nt = template.New(tname)
	}

	return nt.Parse(string(buf))
}
Beispiel #12
0
/*
** Render a template string with given data
 */
func ParseTemplate(tmpl string, data metadata.Metamap) (string, error) {
	var buf bytes.Buffer
	var tpl *template.Template

	tpl = createTemplate()
	tpl, err := tpl.Parse(tmpl)
	if err != nil {
		return "", err
	}

	err = tpl.Execute(&buf, data)
	if err != nil {
		return "", err
	}
	return buf.String(), nil
}
Beispiel #13
0
// Parse parses declared templates.
func Parse(t *template.Template) (*template.Template, error) {
	for name, s := range templates {
		var tmpl *template.Template
		if t == nil {
			t = template.New(name)
		}
		if name == t.Name() {
			tmpl = t
		} else {
			tmpl = t.New(name)
		}
		if _, err := tmpl.Parse(s); err != nil {
			return nil, err
		}
	}
	return t, nil
}
Beispiel #14
0
func packTemplate(tplPack *template.Template, name string) (tpl *template.Template) {

	cwd, err := os.Getwd()
	M.PANIC_ON_ERR(err)

	f, err := os.Open(fmt.Sprintf("%s/%s.html", path.Join(cwd, "templates"), name))
	M.PANIC_ON_ERR(err)
	defer f.Close()

	html, err := ioutil.ReadAll(f)
	M.PANIC_ON_ERR(err)

	tpl, err = tplPack.Parse(string(html))
	M.PANIC_ON_ERR(err)

	return
}
Beispiel #15
0
func parseData(temp *template.Template, reader io.ReadCloser) (*template.Template, error) {
	data, err := ioutil.ReadAll(reader)
	if err != nil {
		return temp, err
	}
	reader.Close()

	if len(data) > 0 {
		if temp == nil {
			x := template.New("new")
			x.Parse(string(data))
			return x, nil
		} else {
			temp.Parse(string(data))
			return temp, nil
		}
	}
	return temp, fmt.Errorf("no data")
}
Beispiel #16
0
func CreateTemplate(name string, allTemplates []string, funcMap template.FuncMap) (*template.Template, error) {
	var (
		tmpl *template.Template
		err  error
	)

	leading := regexp.MustCompile("(\n)?[ \t]*[{]{2}[-][ ]*")
	trailing := regexp.MustCompile("[ ]*[-][}]{2}[ \t]*(\n)?")

	tmpl = template.New(name).Funcs(funcMap)
	for _, code := range allTemplates {
		code = leading.ReplaceAllString(code, "{{")
		code = trailing.ReplaceAllString(code, "}}")
		tmpl, err = tmpl.Parse(code)
		if err != nil {
			return nil, err
		}
	}

	return tmpl, nil
}
Beispiel #17
0
//loadTemplate 加载解析模板
func (d *dynamic) loadTemplate(currDir string) (*template.Template, error) {
	if len(d.Template) == 0 {
		return nil, fmt.Errorf(ErrorPageNotTemplate)
	}
	var (
		t                           *template.Template = nil
		filePath, fileName, content string
		b                           []byte
		err                         error
	)

	for _, filename := range d.Template {
		filePath = filepath.Join(currDir, filename)
		fileName = filepath.Base(filename)

		b, err = ioutil.ReadFile(filePath)
		if err != nil {
			return nil, err
		}
		content = d.formatTemplate(string(b))

		var tmpl *template.Template
		if t == nil {
			t = template.New(fileName)
		}
		if fileName == t.Name() {
			tmpl = t
		} else {
			tmpl = t.New(fileName)
		}
		tmpl.Delims(d.Delims.Left, d.Delims.Right)
		tmpl.Funcs(TemplateFuncMap)
		_, err = tmpl.Parse(content)
		if err != nil {
			return nil, err
		}
	}
	return t, nil
}
Beispiel #18
0
// GetTemplate is used to get a ready to use template based on the url and on
// other sent templates
func GetTemplate(r *http.Request, functions template.FuncMap, templates ...string) (*template.Template, error) {
	// If this is a pjax request, use the minimal template to send only
	// the main content
	if r.Header.Get("X-PJAX") == "true" {
		templates = append(templates, "base_minimal")
	} else {
		templates = append(templates, "base_full")
	}

	var tpl *template.Template

	// For each template, add it to the the tpl variable
	for i, t := range templates {
		// Get the template from the assets
		page, err := assets.Asset("templates/" + t + ".tmpl")

		// Check if there is some error. If so, the template doesn't exist
		if err != nil {
			log.Print(err)
			return new(template.Template), err
		}

		// If it's the first iteration, creates a new template and add the
		// functions map
		if i == 0 {
			tpl, err = template.New(t).Funcs(functions).Parse(string(page))
		} else {
			tpl, err = tpl.Parse(string(page))
		}

		if err != nil {
			log.Print(err)
			return new(template.Template), err
		}
	}

	return tpl, nil
}
Beispiel #19
0
// Returns a copy of the root template with the supplied template merged in.
func (ts *Templates) mergeTemplate(t *template.Template) (out *template.Template, err error) {
	defer func() {
		if r := recover(); r != nil {
			// Seems to be a bug with cloning empty templates.
			err = fmt.Errorf("Problem cloning template: %v", r)
		}
	}()
	if ts.empty {
		out = template.New("root")
	} else {
		if out, err = ts.root.Clone(); err != nil {
			return
		}
	}
	for _, tmpl := range t.Templates() {
		ptr := out.Lookup(tmpl.Name())
		if ptr == nil {
			out.Parse(fmt.Sprintf(`{{define "%v"}}{{end}}`, tmpl.Name()))
			ptr = out.Lookup(tmpl.Name())
		}
		var clone *template.Template
		if clone, err = tmpl.Clone(); err != nil {
			return
		}
		(*ptr) = *clone
		// Merge existing root templates back into new template.
		for _, out_tmpl := range out.Templates() {
			ptr2 := clone.Lookup(out_tmpl.Name())
			if ptr2 == nil {
				clone.Parse(fmt.Sprintf(`{{define "%v"}}{{end}}`, out_tmpl.Name()))
				ptr2 = clone.Lookup(out_tmpl.Name())
				(*ptr2) = *out_tmpl
			}
		}
	}
	return
}
Beispiel #20
0
func jsonClient(t *template.Template) (*template.Template, error) {
	return t.Parse(`
{{ define "json" }}
{{ template "header" $ }}

// {{ .Name }} is a client for {{ .FullName }}.
type {{ .Name }} struct {
  client *aws.JSONClient
}

// New returns a new {{ .Name }} client.
func New(creds aws.CredentialsProvider, region string, client *http.Client) *{{ .Name }} {
  if client == nil {
     client = http.DefaultClient
  }

  endpoint, service, region := endpoints.Lookup("{{ .Metadata.EndpointPrefix }}", region)

  return &{{ .Name }}{
    client: &aws.JSONClient{
      Context: aws.Context{
        Credentials: creds,
        Service: service,
        Region: region,
      },      Client: client,
      Endpoint: endpoint,
      JSONVersion: "{{ .Metadata.JSONVersion }}",
      TargetPrefix: "{{ .Metadata.TargetPrefix }}",
    },
  }
}

{{ range $name, $op := .Operations }}

{{ godoc $name $op.Documentation }} func (c *{{ $.Name }}) {{ exportable $name }}({{ if $op.Input }}req {{ $op.Input.Type }}{{ end }}) ({{ if $op.Output }}resp {{ $op.Output.Type }},{{ end }} err error) {
  {{ if $op.Output }}resp = {{ $op.Output.Literal }}{{ else }}// NRE{{ end }}
  err = c.client.Do("{{ $name }}", "{{ $op.HTTP.Method }}", "{{ $op.HTTP.RequestURI }}", {{ if $op.Input }} req {{ else }} nil {{ end }}, {{ if $op.Output }} resp {{ else }} nil {{ end }})
  return
}

{{ end }}

{{ range $name, $s := .Shapes }}
{{ if eq $s.ShapeType "structure" }}
{{ if not $s.Exception }}

// {{ exportable $name }} is undocumented.
type {{ exportable $name }} struct {
{{ range $name, $m := $s.Members }}
{{ exportable $name }} {{ $m.Type }} {{ $m.JSONTag }}  {{ end }}
}

{{ end }}
{{ else if $s.Enum }}
// Possible values for {{ $.Name }}.
const (
{{ range $name, $value := $s.Enums }}
{{ $name }} = {{ $value }}{{ end }}
)
{{ end }}
{{ end }}

{{ template "footer" }}
{{ end }}

`)
}
Beispiel #21
0
func queryClient(t *template.Template) (*template.Template, error) {
	return t.Parse(`
{{ define "query" }}
{{ template "header" $ }}

import (
	"io"
	"encoding/xml"
)

// {{ .Name }} is a client for {{ .FullName }}.
type {{ .Name }} struct {
  client *aws.QueryClient
}

// New returns a new {{ .Name }} client.
func New(creds aws.CredentialsProvider, region string, client *http.Client) *{{ .Name }} {
  if client == nil {
     client = http.DefaultClient
  }

  endpoint, service, region := endpoints.Lookup("{{ .Metadata.EndpointPrefix }}", region)

  return &{{ .Name }}{
    client: &aws.QueryClient{
      Context: aws.Context{
        Credentials: creds,
        Service: service,
        Region: region,
      },
      Client: client,
      Endpoint: endpoint,
      APIVersion: "{{ .Metadata.APIVersion }}",
    },
  }
}

{{ range $name, $op := .Operations }}

{{ godoc $name $op.Documentation }} func (c *{{ $.Name }}) {{ exportable $name }}({{ if $op.InputRef }}req {{ $op.InputRef.WrappedType }}{{ end }}) ({{ if $op.OutputRef }}resp {{ $op.OutputRef.WrappedType }},{{ end }} err error) {
  {{ if $op.Output }}resp = {{ $op.OutputRef.WrappedLiteral }}{{ else }}// NRE{{ end }}
  err = c.client.Do("{{ $name }}", "{{ $op.HTTP.Method }}", "{{ $op.HTTP.RequestURI }}", {{ if $op.Input }} req {{ else }} nil {{ end }}, {{ if $op.Output }} resp {{ else }} nil {{ end }})
  return
}

{{ end }}

{{ range $name, $s := .Shapes }}
{{ if eq $s.ShapeType "map" }}

type {{ exportable $name }} map[{{ $s.Key.ElementType }}]{{ $s.Value.ElementType }}

// UnmarshalXML implements xml.UnmarshalXML interface for map
func (m *{{ exportable $name }}) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
	if *m == nil {
		(*m) = make({{ exportable $name }})
	}
	for {
		var e struct {
			{{ or $s.KeyRef.LocationName "Key" }} {{ $s.Key.ElementType }} {{ $s.KeyXMLTag }}
			{{ or $s.ValueRef.LocationName "Value" }} {{ $s.Value.ElementType }} {{ $s.ValueXMLTag }}
		}
		err := d.DecodeElement(&e, &start)
		if err != nil && err != io.EOF {
			return err
		}
		if err == io.EOF {
			break
		}
		(*m)[e.{{ or $s.KeyRef.LocationName "Key" }}] = e.{{ or $s.ValueRef.LocationName "Value" }}
	}
	return nil
}
{{ end }}

{{ if eq $s.ShapeType "structure" }}
{{ if not $s.Exception }}

// {{ exportable $name }} is undocumented.
type {{ exportable $name }} struct {
{{ range $name, $m := $s.Members }}
{{ exportable $name }} {{ $m.Type }} {{ $m.QueryTag $s.ResultWrapper }}  {{ end }}
}

{{ end }}
{{ else if $s.Enum }}
// Possible values for {{ $.Name }}.
const (
{{ range $name, $value := $s.Enums }}
{{ $name }} = {{ $value }}{{ end }}
)
{{ end }}
{{ end }}

{{ range $wname, $s := .Wrappers }}

// {{ exportable $wname }} is a wrapper for {{ $s.Name }}.
type {{ exportable $wname }} struct {
{{ range $name, $m := $s.Members }}
{{ exportable $name }} {{ $m.Type }} {{ $m.QueryTag $wname }}  {{ end }}
}

{{ end }}

{{ template "footer" }}
var _ xml.Decoder
var _ = io.EOF
{{ end }}

`)
}
Beispiel #22
0
// mainLoop initiates all ports and handles the traffic
func mainLoop() {
	openPorts()
	defer closePorts()

	waitCh := make(chan bool)
	go func() {
		total := 0
		for {
			select {
			case v := <-inCh:
				if !v {
					log.Println("IN port is closed. Interrupting execution")
					exitCh <- syscall.SIGTERM
					break
				} else {
					total++
				}
			case v := <-outCh:
				if !v {
					log.Println("OUT port is closed. Interrupting execution")
					exitCh <- syscall.SIGTERM
					break
				} else {
					total++
				}
			}
			if total >= 2 && waitCh != nil {
				waitCh <- true
			}
		}
	}()

	log.Println("Waiting for port connections to establish... ")
	select {
	case <-waitCh:
		log.Println("Ports connected")
		waitCh = nil
	case <-time.Tick(30 * time.Second):
		log.Println("Timeout: port connections were not established within provided interval")
		exitCh <- syscall.SIGTERM
		return
	}

	log.Println("Waiting for template...")
	var (
		t  *template.Template
		ip [][]byte
	)
	for {
		ip, err = tplPort.RecvMessageBytes(0)
		if err != nil {
			continue
		}
		if !runtime.IsValidIP(ip) {
			log.Println("Invalid IP:", ip)
			continue
		}
		t = template.New("Current template")
		t, err = t.Parse(string(ip[1]))
		if err != nil {
			log.Println("Failed to configure component:", err.Error())
			continue
		}
		break
	}
	tplPort.Close()

	log.Println("Started...")
	var (
		buf  *bytes.Buffer
		data map[string]interface{}
	)
	for {
		ip, err := inPort.RecvMessageBytes(0)
		if err != nil {
			continue
		}
		if !runtime.IsValidIP(ip) {
			continue
		}

		err = json.Unmarshal(ip[1], &data)
		if err != nil {
			log.Println(err.Error())
			continue
		}

		buf = bytes.NewBufferString("")
		err = t.Execute(buf, data)
		if err != nil {
			log.Println(err.Error())
			continue
		}

		outPort.SendMessage(runtime.NewPacket(buf.Bytes()))
	}
}
Beispiel #23
0
func restCommon(t *template.Template) (*template.Template, error) {
	return t.Parse(`
{{ define "rest-uri" }}
  {{ if .Input }}
  {{ range $name, $m := .Input.Members }}
  {{ if eq $m.Location "uri" }}

  if req.{{ exportable $name }} != nil {
    uri = strings.Replace(uri, "{"+"{{ $m.LocationName }}"+"}", aws.EscapePath(*req.{{ exportable $name }}), -1)
    uri = strings.Replace(uri, "{"+"{{ $m.LocationName }}+"+"}", aws.EscapePath(*req.{{ exportable $name }}), -1)
  }

  {{ end }}
  {{ end }}
  {{ end }}

{{ end }}


{{ define "rest-querystring" }}
  q := url.Values{}

  {{ if .Input }}
  {{ range $name, $m := .Input.Members }}
  {{ if eq $m.Location "querystring" }}


  {{ if eq $m.Shape.ShapeType "string" }}

  if req.{{ exportable $name }} != nil {
    q.Set("{{ $m.LocationName }}", *req.{{ exportable $name }})
  }

  {{ else if eq $m.Shape.ShapeType "timestamp" }}

  if req.{{ exportable $name }} != (time.Time{}) {
    q.Set("{{ $m.LocationName }}", req.{{ exportable $name }}.Format(time.RFC822))
  }

  {{ else if eq $m.Shape.ShapeType "integer" }}

  if req.{{ exportable $name }} != nil {
    q.Set("{{ $m.LocationName }}", strconv.Itoa(*req.{{ exportable $name }}))
  }

  {{ else }}

  if req.{{ exportable $name }} != nil {
    q.Set("{{ $m.LocationName }}", fmt.Sprintf("%v", req.{{ exportable $name }}))
  }

  {{ end }}

  {{ end }}
  {{ end }}
  {{ end }}

  if len(q) > 0 {
    uri += "?" + q.Encode()
  }
{{ end }}

{{ define "rest-reqheaders" }}
  {{ if .Input }}
  {{ range $name, $m := .Input.Members }}
  {{ if eq $m.Location "header" }}

 {{ if eq $m.Shape.ShapeType "string" }}

  if req.{{ exportable $name }} != nil {
    httpReq.Header.Set("{{ $m.LocationName }}", *req.{{ exportable $name }})
  }

  {{ else if eq $m.Shape.ShapeType "timestamp" }}

  if req.{{ exportable $name }} != (time.Time{}) {
    httpReq.Header.Set("{{ $m.LocationName }}", req.{{ exportable $name }}.Format(time.RFC822))
  }

  {{ else if eq $m.Shape.ShapeType "integer" }}

  {{ if eq $m.LocationName "Content-Length" }}

  if req.{{ exportable $name }} != nil {
    httpReq.ContentLength = *req.{{ exportable $name }}
  }

  {{ else }}

  if req.{{ exportable $name }} != nil {
    httpReq.Header.Set("{{ $m.LocationName }}", strconv.Itoa(*req.{{ exportable $name }}))
  }

  {{ end }}

  {{ else }}

  if req.{{ exportable $name }} != nil {
    httpReq.Header.Set("{{ $m.LocationName }}", fmt.Sprintf("%v", req.{{ exportable $name }}))
  }

  {{ end }}

  {{ else if eq $m.Location "headers" }}

  for name, value := range req.{{ exportable $name }} {
	httpReq.Header.Set(name, value)
  }

  {{ end }}
  {{ end }}
  {{ end }}
{{ end }}

{{ define "rest-respheaders" }}
 {{ range $name, $m := .Output.Members }}
    {{ if ne $name "Body" }}
      {{ if eq $m.Location "header" }}
        if s := httpResp.Header.Get("{{ $m.LocationName }}"); s != "" {
         {{ if eq $m.Shape.ShapeType "string" }}
          resp.{{ exportable $name }} = &s
         {{ else if eq $m.Shape.ShapeType "timestamp" }}
           var t time.Time
           t, err = time.Parse(time.RFC1123, s)
           if err != nil {
             return
           }
           resp.{{ exportable $name }} = t
         {{ else if eq $m.Shape.ShapeType "integer" }}
           {{ if eq $m.Shape.Name "ContentLength" }}
           var n int64
           n, err = strconv.ParseInt(s, 10, 64)
           {{ else }}
           var n int
           n, err = strconv.Atoi(s)
           {{ end }}
           if  err != nil {
             return
           }
           resp.{{ exportable $name }} = &n
         {{ else if eq $m.Shape.ShapeType "boolean" }}
           var v bool
           v, err = strconv.ParseBool(s)
           if  err != nil {
             return
            }
           resp.{{ exportable $name }} = &v
         {{ else }}
         // TODO: add support for {{ $m.Shape.ShapeType }} headers
         {{ end }}
        }
      {{ else if eq $m.Location "headers" }}
      resp.{{ exportable $name }} = {{ $m.Shape.Type }}{}
      for name := range httpResp.Header {
        if strings.HasPrefix(name, "X-Amz-Meta-") {
          resp.{{ exportable $name }}[name] = httpResp.Header.Get(name)
        }
      }
      {{ else if eq $m.Location "statusCode" }}
        resp.{{ exportable $name }} = aws.Integer(httpResp.StatusCode)
      {{ else if ne $m.Location "" }}
      // TODO: add support for extracting output members from {{ $m.Location }} to support {{ exportable $name }}
      {{ end }}

    {{ end }}
  {{ end }}
{{ end }}
`)
}
Beispiel #24
0
func restJSONClient(t *template.Template) (*template.Template, error) {
	return t.Parse(`
{{ define "rest-json" }}
{{ template "header" $ }}

import (
  "bytes"
  "encoding/json"
  "fmt"
  "io"
  "io/ioutil"
  "net/url"
  "strconv"
  "strings"
)

// {{ .Name }} is a client for {{ .FullName }}.
type {{ .Name }} struct {
  client *aws.RestClient
}

// New returns a new {{ .Name }} client.
func New(creds aws.CredentialsProvider, region string, client *http.Client) *{{ .Name }} {
  if client == nil {
     client = http.DefaultClient
  }

  endpoint, service, region := endpoints.Lookup("{{ .Metadata.EndpointPrefix }}", region)

  return &{{ .Name }}{
    client: &aws.RestClient{
      Context: aws.Context{
        Credentials: creds,
        Service: service,
        Region: region,
      },
      Client: client,
      Endpoint: endpoint,
      APIVersion: "{{ .Metadata.APIVersion }}",
    },
  }
}

{{ range $name, $op := .Operations }}

{{ godoc $name $op.Documentation }} func (c *{{ $.Name }}) {{ exportable $name }}({{ if $op.Input }}req {{ $op.Input.Type }}{{ end }}) ({{ if $op.Output }}resp {{ $op.Output.Type }},{{ end }} err error) {
  {{ if $op.Output }}resp = {{ $op.Output.Literal }}{{ else }}// NRE{{ end }}

  var body io.Reader
  var contentType string
  {{ if $op.Input }}
  {{ if $op.Input.Payload }}
  {{ with $m := index $op.Input.Members $op.Input.Payload }}
  {{ if $m.Streaming }}
  body = req.{{ exportable $m.Name  }}
  {{ else }}
  contentType = "application/json"
  b, err := json.Marshal(req.{{ exportable $m.Name  }})
  if err != nil {
    return
  }
  body = bytes.NewReader(b)
  {{ end }}
  {{ end }}
  {{ end }}
  {{ end }}


  uri := c.client.Endpoint + "{{ $op.HTTP.RequestURI }}"
  {{ template "rest-uri" $op }}

  {{ template "rest-querystring" $op }}

  httpReq, err := http.NewRequest("{{ $op.HTTP.Method }}", uri, body)
  if err != nil {
    return
  }

  if contentType != "" {
    httpReq.Header.Set("Content-Type", contentType)
  }

  {{ template "rest-reqheaders" $op }}

  httpResp, err := c.client.Do(httpReq)
  if err != nil {
    return
  }

  {{ if $op.Output }}
    {{ with $name := "Body" }}
    {{ with $m := index $op.Output.Members $name }}
    {{ if $m }}

      {{ if $m.Streaming }}
  resp.Body = httpResp.Body
      {{ else }}
  defer httpResp.Body.Close()

  if e := json.NewDecoder(httpResp.Body).Decode(resp); e != nil && e != io.EOF {
    err = e
    return
  }

      {{ end }}


    {{ else }}
  defer httpResp.Body.Close()
    {{ end }}
    {{ end }}

   {{ template "rest-respheaders" $op }}
  {{ end }}
  {{ else }}
  defer httpResp.Body.Close()
  {{ end }}


  return
}

{{ end }}

{{ range $name, $s := .Shapes }}
{{ if eq $s.ShapeType "structure" }}
{{ if not $s.Exception }}

// {{ exportable $name }} is undocumented.
type {{ exportable $name }} struct {
{{ range $name, $m := $s.Members }}
{{ exportable $name }} {{ $m.Type }} {{ $m.JSONTag }}  {{ end }}
}

{{ end }}
{{ else if $s.Enum }}
// Possible values for {{ $.Name }}.
const (
{{ range $name, $value := $s.Enums }}
{{ $name }} = {{ $value }}{{ end }}
)
{{ end }}
{{ end }}

{{ template "footer" }}
var _ bytes.Reader
var _ url.URL
var _ fmt.Stringer
var _ strings.Reader
var _ strconv.NumError
var _ = ioutil.Discard
var _ json.RawMessage
{{ end }}
`)
}