<commit_before>package main

import (
	"fmt"
	"io/ioutil"
	"strings"

	yaml "gopkg.in/yaml.v2"

	"github.com/rosenhouse/cf-filler/vars"
)

type Recipe struct {
	Strings        map[string]string            `yaml:"strings"`
	Passwords      []string                     `yaml:"passwords"`
	PasswordArrays []*vars.PasswordArray        `yaml:"password_arrays"`
	SSHKeys        []*vars.SSHKeyAndFingerprint `yaml:"ssh_keys"`
	BasicKeyPairs  []*vars.BasicKeyPair         `yaml:"basic_key_pairs"`
	CertSets       []*vars.CertSet              `yaml:"cert_sets"`
}

func LoadRecipe(path string) (*Recipe, error) {
	yamlBytes, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, fmt.Errorf("reading recipe file: %s", err)
	}

	recipe := &Recipe{}
	err = yaml.Unmarshal(yamlBytes, recipe)
	return recipe, err
}

func (recipe *Recipe) MakeAllVars(systemDomain, mysqlHost string) (DeploymentVars, error) {
	o := DeploymentVars{}
	o["system_domain"] = systemDomain

	for varName, template := range recipe.Strings {
		o[varName] = strings.Replace(template, "((system_domain))", systemDomain, -1)
	}

	o.GeneratePasswords(recipe.Passwords...)

	for _, pa := range recipe.PasswordArrays {
		o.GeneratePasswordArray(pa)
	}

	for _, certSet := range recipe.CertSets {
		if err := o.GenerateCerts(certSet); err != nil {
			return o, fmt.Errorf("generate cert set: %s", err)
		}
	}

	for _, kp := range recipe.BasicKeyPairs {
		if err := o.GenerateBasicKeyPair(kp); err != nil {
			return o, fmt.Errorf("generate key pair: %s", err)
		}
	}

	for _, kaf := range recipe.SSHKeys {
		if err := o.GenerateSSHKeyAndFingerprint(kaf); err != nil {
			return o, fmt.Errorf("generate ssh creds: %s", err)
		}
	}

	o["diego_bbs_sql_db_connection_string"] = fmt.Sprintf("%s:%s@tcp(%s:3306)/diego",
		o["cf_mysql_mysql_seeded_databases_diego_username"],
		o["cf_mysql_mysql_seeded_databases_diego_password"],
		mysqlHost)

	return o, nil
}
<commit_msg>Update recipe.go<commit_after>package main

import (
	"fmt"
	"io/ioutil"
	"strings"

	yaml "gopkg.in/yaml.v2"

	"github.com/rosenhouse/cf-filler/vars"
)

type Recipe struct {
	Strings        map[string]string            `yaml:"strings"`
	Passwords      []string                     `yaml:"passwords"`
	PasswordArrays []*vars.PasswordArray        `yaml:"password_arrays"`
	SSHKeys        []*vars.SSHKeyAndFingerprint `yaml:"ssh_keys"`
	BasicKeyPairs  []*vars.BasicKeyPair         `yaml:"basic_key_pairs"`
	CertSets       []*vars.CertSet              `yaml:"cert_sets"`
}

func LoadRecipe(path string) (*Recipe, error) {
	yamlBytes, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, fmt.Errorf("reading recipe file: %s", err)
	}

	recipe := &Recipe{}
	err = yaml.Unmarshal(yamlBytes, recipe)
	return recipe, err
}

func (recipe *Recipe) MakeAllVars(systemDomain, mysqlHost string) (DeploymentVars, error) {
	o := DeploymentVars{}
	o["system_domain"] = systemDomain

	for varName, template := range recipe.Strings {
		o[varName] = strings.Replace(template, "((system_domain))", systemDomain, -1)
	}

	o.GeneratePasswords(recipe.Passwords...)

	for _, pa := range recipe.PasswordArrays {
		o.GeneratePasswordArray(pa)
	}

	for _, certSet := range recipe.CertSets {
		if err := o.GenerateCerts(certSet); err != nil {
			return o, fmt.Errorf("generate cert set: %s", err)
		}
	}

	for _, kp := range recipe.BasicKeyPairs {
		if err := o.GenerateBasicKeyPair(kp); err != nil {
			return o, fmt.Errorf("generate key pair: %s", err)
		}
	}

	for _, kaf := range recipe.SSHKeys {
		if err := o.GenerateSSHKeyAndFingerprint(kaf); err != nil {
			return o, fmt.Errorf("generate ssh creds: %s", err)
		}
	}

	return o, nil
}
<|endoftext|>


<commit_before>// Copyright 2015 LinkedIn Corp. Licensed under the Apache License,
// Version 2.0 (the "License"); you may not use this file except in
// compliance with the License.
 You may obtain a copy of the License
// at http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
//
distributed under the License is distributed on an "AS IS" BASIS,
//
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied.Copyright [201X] LinkedIn Corp. Licensed under the Apache
// License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License.
 You may obtain a copy of
// the License at http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
//
distributed under the License is distributed on an "AS IS" BASIS,
//
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied.

package goavro

import (
	"encoding/json"
	"fmt"
	"strings"
)

// Record is an abstract data type used to hold data corresponding to
// an Avro record. Wherever an Avro schema specifies a record, this
// library's Decode method will return a Record initialized to the
// record's values read from the io.Reader. Likewise, when using
// Encode to convert data to an Avro record, it is necessary to create
// and send a Record instance to the Encoder method.
type Record struct {
	Name      string
	Fields    []*recordField
	aliases   []string
	doc       string
	n         *name
	ens       string
	schemaMap map[string]interface{}
}

// Get returns the datum of the specified Record field.
func (r Record) Get(fieldName string) (interface{}, error) {
	// qualify fieldName searches based on record namespace
	fn, _ := newName(nameName(fieldName), nameNamespace(r.n.ns))

	for _, field := range r.Fields {
		if field.Name == fn.n {
			return field.Datum, nil
		}
	}
	return nil, fmt.Errorf("no such field: %s", fieldName)
}

// GetFieldSchema returns the schema of the specified Record field.
func (r Record) GetFieldSchema(fieldName string) (interface{}, error) {
	// qualify fieldName searches based on record namespace
	fn, _ := newName(nameName(fieldName), nameNamespace(r.n.ns))

	for _, field := range r.Fields {
		if field.Name == fn.n {
			return field.schema, nil
		}
	}
	return nil, fmt.Errorf("no such field: %s", fieldName)
}

// Set updates the datum of the specified Record field.
func (r Record) Set(fieldName string, value interface{}) error {
	// qualify fieldName searches based on record namespace
	fn, _ := newName(nameName(fieldName), nameNamespace(r.n.ns))

	for _, field := range r.Fields {
		if field.Name == fn.n {
			field.Datum = value
			return nil
		}
	}
	return fmt.Errorf("no such field: %s", fieldName)
}

// String returns a string representation of the Record.
func (r Record) String() string {
	fields := make([]string, len(r.Fields))
	for idx, f := range r.Fields {
		fields[idx] = fmt.Sprintf("%v", f)
	}
	return fmt.Sprintf("{%s: [%v]}", r.Name, strings.Join(fields, ", "))
}

// NewRecord will create a Record instance corresponding to the
// specified schema.
//
//    func recordExample(codec goavro.Codec, w io.Writer, recordSchema string) error {
//         // To encode a Record, you need to instantiate a Record instance
//         // that adheres to the schema the Encoder expect.
//         someRecord, err := goavro.NewRecord(goavro.RecordSchema(recordSchema))
//         if err != nil {
//             return err
//         }
//         // Once you have a Record, you can set the values of the various fields.
//         someRecord.Set("username", "Aquaman")
//         someRecord.Set("comment", "The Atlantic is oddly cold this morning!")
//         // Feel free to fully qualify the field name if you'd like
//         someRecord.Set("com.example.timestamp", int64(1082196484))
//
//         // Once the fields of the Record have the correct data, you can encode it
//         err = codec.Encode(w, someRecord)
//         return err
//     }
func NewRecord(setters ...RecordSetter) (*Record, error) {
	record := &Record{n: &name{}}
	for _, setter := range setters {
		err := setter(record)
		if err != nil {
			return nil, err
		}
	}
	if record.schemaMap == nil {
		return nil, newCodecBuildError("record", "no schema defined")
	}
	var err error
	record.n, err = newName(nameSchema(record.schemaMap), nameEnclosingNamespace(record.ens))
	if err != nil {
		return nil, newCodecBuildError("record", err)
	}
	record.Name = record.n.n
	ns := record.n.namespace()

	val, ok := record.schemaMap["fields"]
	if !ok {
		return nil, newCodecBuildError("record", "record requires one or more fields")
	}
	fields, ok := val.([]interface{})
	if !ok || len(fields) == 0 {
		return nil, newCodecBuildError("record", "record fields ought to be non-empty array")
	}

	record.Fields = make([]*recordField, len(fields))
	for i, field := range fields {
		rf, err := newRecordField(field, recordFieldEnclosingNamespace(ns))
		if err != nil {
			return nil, newCodecBuildError("record", err)
		}
		record.Fields[i] = rf
	}

	// fields optional to the avro spec

	if val, ok = record.schemaMap["doc"]; ok {
		record.doc, ok = val.(string)
		if !ok {
			return nil, newCodecBuildError("record", "doc ought to be string")
		}
	}
	if val, ok = record.schemaMap["aliases"]; ok {
		record.aliases, ok = val.([]string)
		if !ok {
			return nil, newCodecBuildError("record", "aliases ought to be array of strings")
		}
	}
	record.schemaMap = nil
	return record, nil
}

// RecordSetter functions are those those which are used to
// instantiate a new Record.
type RecordSetter func(*Record) error

// recordSchemaRaw specifies the schema of the record to create. Schema
// must be `map[string]interface{}`.
func recordSchemaRaw(schema interface{}) RecordSetter {
	return func(r *Record) error {
		var ok bool
		r.schemaMap, ok = schema.(map[string]interface{})
		if !ok {
			return newCodecBuildError("record", "expected: map[string]interface{}; received: %T", schema)
		}
		return nil
	}
}

// RecordSchema specifies the schema of the record to
// create. Schema must be a JSON string.
func RecordSchema(recordSchemaJSON string) RecordSetter {
	return func(r *Record) error {
		var schema interface{}
		err := json.Unmarshal([]byte(recordSchemaJSON), &schema)
		if err != nil {
			return newCodecBuildError("record", err)
		}
		var ok bool
		r.schemaMap, ok = schema.(map[string]interface{})
		if !ok {
			return newCodecBuildError("record", "expected: map[string]interface{}; received: %T", schema)
		}
		return nil
	}
}

// RecordEnclosingNamespace specifies the enclosing namespace of the
// record to create. For instance, if the enclosing namespace is
// `com.example`, and the record name is `Foo`, then the full record
// name will be `com.example.Foo`.
func RecordEnclosingNamespace(someNamespace string) RecordSetter {
	return func(r *Record) error {
		r.ens = someNamespace
		return nil
	}
}

////////////////////////////////////////

type recordField struct {
	Name       string
	Datum      interface{}
	doc        string
	defval     interface{}
	hasDefault bool
	order      string
	aliases    []string
	schema     interface{}
	ens        string
}

func (rf recordField) String() string {
	return fmt.Sprintf("%s: %v", rf.Name, rf.Datum)
}

type recordFieldSetter func(*recordField) error

func recordFieldEnclosingNamespace(someNamespace string) recordFieldSetter {
	return func(rf *recordField) error {
		rf.ens = someNamespace
		return nil
	}
}

func newRecordField(schema interface{}, setters ...recordFieldSetter) (*recordField, error) {
	schemaMap, ok := schema.(map[string]interface{})
	if !ok {
		return nil, newCodecBuildError("record field", "schema expected: map[string]interface{}; received: %T", schema)
	}

	rf := &recordField{}
	for _, setter := range setters {
		err := setter(rf)
		if err != nil {
			return nil, newCodecBuildError("record field", err)
		}
	}

	n, err := newName(nameSchema(schemaMap), nameEnclosingNamespace(rf.ens))
	if err != nil {
		return nil, newCodecBuildError("record field", err)
	}
	rf.Name = n.n

	typeName, ok := schemaMap["type"]
	if !ok {
		return nil, newCodecBuildError("record field", "ought to have type key")
	}
	rf.schema = schema

	// fields optional to the avro spec

	val, ok := schemaMap["default"]
	if ok {
		rf.hasDefault = true
		switch typeName.(type) {
		case string:
			switch typeName {
			case "int":
				dv, ok := val.(float64)
				if !ok {
					return nil, newCodecBuildError("record field", "default value type mismatch: %s; expected: %s; received: %T", rf.Name, "int32", val)
				}
				rf.defval = int32(dv)
			case "long":
				dv, ok := val.(float64)
				if !ok {
					return nil, newCodecBuildError("record field", "default value type mismatch: %s; expected: %s; received: %T", rf.Name, "int64", val)
				}
				rf.defval = int64(dv)
			case "float":
				dv, ok := val.(float64)
				if !ok {
					return nil, newCodecBuildError("record field", "default value type mismatch: %s; expected: %s; received: %T", rf.Name, "float32", val)
				}
				rf.defval = float32(dv)
			case "bytes":
				dv, ok := val.(string)
				if !ok {
					return nil, newCodecBuildError("record field", "default value type mismatch: %s; expected: %s; received: %T", rf.Name, "string", val)
				}
				rf.defval = []byte(dv)
			default:
				rf.defval = val
			}
		default:
			rf.defval = val
		}
	}

	if val, ok = schemaMap["doc"]; ok {
		rf.doc, ok = val.(string)
		if !ok {
			return nil, newCodecBuildError("record field", "record field doc ought to be string")
		}
	}

	if val, ok = schemaMap["order"]; ok {
		rf.order, ok = val.(string)
		if !ok {
			return nil, newCodecBuildError("record field", "record field order ought to be string")
		}
		switch rf.order {
		case "ascending", "descending", "ignore":
			// ok
		default:
			return nil, newCodecBuildError("record field", "record field order ought to bescending, descending, or ignore")
		}
	}

	if val, ok = schemaMap["aliases"]; ok {
		rf.aliases, ok = val.([]string)
		if !ok {
			return nil, newCodecBuildError("record field", "record field aliases ought to be array of strings")
		}
	}

	return rf, nil
}
<commit_msg>ROCANA-2462 Add field accessors that don't qualify names<commit_after>// Copyright 2015 LinkedIn Corp. Licensed under the Apache License,
// Version 2.0 (the "License"); you may not use this file except in
// compliance with the License.
 You may obtain a copy of the License
// at http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
//
distributed under the License is distributed on an "AS IS" BASIS,
//
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied.Copyright [201X] LinkedIn Corp. Licensed under the Apache
// License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License.
 You may obtain a copy of
// the License at http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
//
distributed under the License is distributed on an "AS IS" BASIS,
//
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied.

package goavro

import (
	"encoding/json"
	"fmt"
	"strings"
)

// Record is an abstract data type used to hold data corresponding to
// an Avro record. Wherever an Avro schema specifies a record, this
// library's Decode method will return a Record initialized to the
// record's values read from the io.Reader. Likewise, when using
// Encode to convert data to an Avro record, it is necessary to create
// and send a Record instance to the Encoder method.
type Record struct {
	Name      string
	Fields    []*recordField
	aliases   []string
	doc       string
	n         *name
	ens       string
	schemaMap map[string]interface{}
}

func (r Record) getField(fieldName string) (*recordField, error) {
	for _, field := range r.Fields {
		if field.Name == fieldName {
			return field, nil
		}
	}
	return nil, fmt.Errorf("no such field: %s", fieldName)
}

// GetQualified returns the datum of the specified Record field, without attempting to qualify the name
func (r Record) GetQualified(qualifiedName string) (interface{}, error) {
	field, err := r.getField(qualifiedName)
	if err != nil {
		return nil, err
	}
	return field.Datum, nil
}

// Get returns the datum of the specified Record field.
func (r Record) Get(fieldName string) (interface{}, error) {
	// qualify fieldName searches based on record namespace
	fn, err := newName(nameName(fieldName), nameNamespace(r.n.ns))
	if err != nil {
		return nil, err
	}
	return r.GetQualified(fn.n)
}

// GetFieldSchema returns the schema of the specified Record field.
func (r Record) GetFieldSchema(fieldName string) (interface{}, error) {
	// qualify fieldName searches based on record namespace
	fn, err := newName(nameName(fieldName), nameNamespace(r.n.ns))
	if err != nil {
		return nil, err
	}
	field, err := r.getField(fn.n)
	if err != nil {
		return nil, err
	}
	return field.schema, nil
}

// SetQualified updates the datum of the specified Record field, without attempting to qualify the name
func (r Record) SetQualified(qualifiedName string, value interface{}) error {
	field, err := r.getField(qualifiedName)
	if err != nil {
		return err
	}
	field.Datum = value
	return nil

}

// Set updates the datum of the specified Record field.
func (r Record) Set(fieldName string, value interface{}) error {
	// qualify fieldName searches based on record namespace
	fn, err := newName(nameName(fieldName), nameNamespace(r.n.ns))
	if err != nil {
		return err
	}
	return r.SetQualified(fn.n, value)
}

// String returns a string representation of the Record.
func (r Record) String() string {
	fields := make([]string, len(r.Fields))
	for idx, f := range r.Fields {
		fields[idx] = fmt.Sprintf("%v", f)
	}
	return fmt.Sprintf("{%s: [%v]}", r.Name, strings.Join(fields, ", "))
}

// NewRecord will create a Record instance corresponding to the
// specified schema.
//
//    func recordExample(codec goavro.Codec, w io.Writer, recordSchema string) error {
//         // To encode a Record, you need to instantiate a Record instance
//         // that adheres to the schema the Encoder expect.
//         someRecord, err := goavro.NewRecord(goavro.RecordSchema(recordSchema))
//         if err != nil {
//             return err
//         }
//         // Once you have a Record, you can set the values of the various fields.
//         someRecord.Set("username", "Aquaman")
//         someRecord.Set("comment", "The Atlantic is oddly cold this morning!")
//         // Feel free to fully qualify the field name if you'd like
//         someRecord.Set("com.example.timestamp", int64(1082196484))
//
//         // Once the fields of the Record have the correct data, you can encode it
//         err = codec.Encode(w, someRecord)
//         return err
//     }
func NewRecord(setters ...RecordSetter) (*Record, error) {
	record := &Record{n: &name{}}
	for _, setter := range setters {
		err := setter(record)
		if err != nil {
			return nil, err
		}
	}
	if record.schemaMap == nil {
		return nil, newCodecBuildError("record", "no schema defined")
	}
	var err error
	record.n, err = newName(nameSchema(record.schemaMap), nameEnclosingNamespace(record.ens))
	if err != nil {
		return nil, newCodecBuildError("record", err)
	}
	record.Name = record.n.n
	ns := record.n.namespace()

	val, ok := record.schemaMap["fields"]
	if !ok {
		return nil, newCodecBuildError("record", "record requires one or more fields")
	}
	fields, ok := val.([]interface{})
	if !ok || len(fields) == 0 {
		return nil, newCodecBuildError("record", "record fields ought to be non-empty array")
	}

	record.Fields = make([]*recordField, len(fields))
	for i, field := range fields {
		rf, err := newRecordField(field, recordFieldEnclosingNamespace(ns))
		if err != nil {
			return nil, newCodecBuildError("record", err)
		}
		record.Fields[i] = rf
	}

	// fields optional to the avro spec

	if val, ok = record.schemaMap["doc"]; ok {
		record.doc, ok = val.(string)
		if !ok {
			return nil, newCodecBuildError("record", "doc ought to be string")
		}
	}
	if val, ok = record.schemaMap["aliases"]; ok {
		record.aliases, ok = val.([]string)
		if !ok {
			return nil, newCodecBuildError("record", "aliases ought to be array of strings")
		}
	}
	record.schemaMap = nil
	return record, nil
}

// RecordSetter functions are those those which are used to
// instantiate a new Record.
type RecordSetter func(*Record) error

// recordSchemaRaw specifies the schema of the record to create. Schema
// must be `map[string]interface{}`.
func recordSchemaRaw(schema interface{}) RecordSetter {
	return func(r *Record) error {
		var ok bool
		r.schemaMap, ok = schema.(map[string]interface{})
		if !ok {
			return newCodecBuildError("record", "expected: map[string]interface{}; received: %T", schema)
		}
		return nil
	}
}

// RecordSchema specifies the schema of the record to
// create. Schema must be a JSON string.
func RecordSchema(recordSchemaJSON string) RecordSetter {
	return func(r *Record) error {
		var schema interface{}
		err := json.Unmarshal([]byte(recordSchemaJSON), &schema)
		if err != nil {
			return newCodecBuildError("record", err)
		}
		var ok bool
		r.schemaMap, ok = schema.(map[string]interface{})
		if !ok {
			return newCodecBuildError("record", "expected: map[string]interface{}; received: %T", schema)
		}
		return nil
	}
}

// RecordEnclosingNamespace specifies the enclosing namespace of the
// record to create. For instance, if the enclosing namespace is
// `com.example`, and the record name is `Foo`, then the full record
// name will be `com.example.Foo`.
func RecordEnclosingNamespace(someNamespace string) RecordSetter {
	return func(r *Record) error {
		r.ens = someNamespace
		return nil
	}
}

////////////////////////////////////////

type recordField struct {
	Name       string
	Datum      interface{}
	doc        string
	defval     interface{}
	hasDefault bool
	order      string
	aliases    []string
	schema     interface{}
	ens        string
}

func (rf recordField) String() string {
	return fmt.Sprintf("%s: %v", rf.Name, rf.Datum)
}

type recordFieldSetter func(*recordField) error

func recordFieldEnclosingNamespace(someNamespace string) recordFieldSetter {
	return func(rf *recordField) error {
		rf.ens = someNamespace
		return nil
	}
}

func newRecordField(schema interface{}, setters ...recordFieldSetter) (*recordField, error) {
	schemaMap, ok := schema.(map[string]interface{})
	if !ok {
		return nil, newCodecBuildError("record field", "schema expected: map[string]interface{}; received: %T", schema)
	}

	rf := &recordField{}
	for _, setter := range setters {
		err := setter(rf)
		if err != nil {
			return nil, newCodecBuildError("record field", err)
		}
	}

	n, err := newName(nameSchema(schemaMap), nameEnclosingNamespace(rf.ens))
	if err != nil {
		return nil, newCodecBuildError("record field", err)
	}
	rf.Name = n.n

	typeName, ok := schemaMap["type"]
	if !ok {
		return nil, newCodecBuildError("record field", "ought to have type key")
	}
	rf.schema = schema

	// fields optional to the avro spec

	val, ok := schemaMap["default"]
	if ok {
		rf.hasDefault = true
		switch typeName.(type) {
		case string:
			switch typeName {
			case "int":
				dv, ok := val.(float64)
				if !ok {
					return nil, newCodecBuildError("record field", "default value type mismatch: %s; expected: %s; received: %T", rf.Name, "int32", val)
				}
				rf.defval = int32(dv)
			case "long":
				dv, ok := val.(float64)
				if !ok {
					return nil, newCodecBuildError("record field", "default value type mismatch: %s; expected: %s; received: %T", rf.Name, "int64", val)
				}
				rf.defval = int64(dv)
			case "float":
				dv, ok := val.(float64)
				if !ok {
					return nil, newCodecBuildError("record field", "default value type mismatch: %s; expected: %s; received: %T", rf.Name, "float32", val)
				}
				rf.defval = float32(dv)
			case "bytes":
				dv, ok := val.(string)
				if !ok {
					return nil, newCodecBuildError("record field", "default value type mismatch: %s; expected: %s; received: %T", rf.Name, "string", val)
				}
				rf.defval = []byte(dv)
			default:
				rf.defval = val
			}
		default:
			rf.defval = val
		}
	}

	if val, ok = schemaMap["doc"]; ok {
		rf.doc, ok = val.(string)
		if !ok {
			return nil, newCodecBuildError("record field", "record field doc ought to be string")
		}
	}

	if val, ok = schemaMap["order"]; ok {
		rf.order, ok = val.(string)
		if !ok {
			return nil, newCodecBuildError("record field", "record field order ought to be string")
		}
		switch rf.order {
		case "ascending", "descending", "ignore":
			// ok
		default:
			return nil, newCodecBuildError("record field", "record field order ought to bescending, descending, or ignore")
		}
	}

	if val, ok = schemaMap["aliases"]; ok {
		rf.aliases, ok = val.([]string)
		if !ok {
			return nil, newCodecBuildError("record field", "record field aliases ought to be array of strings")
		}
	}

	return rf, nil
}
<|endoftext|>


<commit_before>package main

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/tls"
	"crypto/x509"
	"encoding/pem"
	"fmt"
	"io"
	"math/big"
	"net"
	"strconv"
	"time"

	quic "github.com/lucas-clemente/quic-go"
	"github.com/nange/easyss/cipherstream"
	"github.com/nange/easyss/socks"
	"github.com/pkg/errors"
	log "github.com/sirupsen/logrus"
)

func (ss *Easyss) Remote() {
	if ss.config.EnableQuic {
		ss.quicServer()
	} else {
		ss.tcpServer()
	}
}

func (ss *Easyss) quicServer() {
	addr := ":" + strconv.Itoa(ss.config.ServerPort)
	ln, err := quic.ListenAddr(addr, generateTLSConfig(), &quic.Config{IdleTimeout: time.Minute})
	if err != nil {
		log.Fatal(err)
	}
	log.Infof("starting remote quic server at %v ...", addr)

	for {
		sess, err := ln.Accept()
		if err != nil {
			log.Error("accept:", err)
			continue
		}
		log.Infof("a new session(ip) is accepted. remote addr:%v\n", sess.RemoteAddr())

		go func(sess quic.Session) {
			for {
				stream, err := sess.AcceptStream()
				if err != nil {
					log.Warnf("session accept stream err, remote addr:%v, message: %+v\n",
						sess.RemoteAddr(), errors.WithStack(err))
					sess.Close(err)
					return
				}

				go func(stream quic.Stream) {
					defer stream.Close()
					log.Infof("a new stream is accepted. stream id:%v\n", stream.StreamID())

					addr, ciphermethod, err := handShake(stream, ss.config.Password)
					if err != nil {
						log.Warnf("get target addr err:%+v", err)
						return
					}
					if addr.String() == "" || ciphermethod == "" {
						log.Errorf("after handshake with client, but get empty addr:%v or ciphermethod:%v",
							addr.String(), ciphermethod)
						return
					}
					log.Infof("target proxy addr is:%v", addr.String())

					tconn, err := net.Dial("tcp", addr.String())
					if err != nil {
						log.Errorf("net.Dial %v err:%v", addr, err)
						return
					}
					defer tconn.Close()

					csStream, err := cipherstream.New(stream, ss.config.Password, ciphermethod)
					if err != nil {
						log.Errorf("new cipherstream err:%+v, password:%v, method:%v",
							err, ss.config.Password, ss.config.Method)
						return
					}

					go func() {
						defer stream.Close()
						defer tconn.Close()
						n, err := io.Copy(csStream, tconn)
						log.Infof("reciveve %v bytes from %v, message:%v", n, addr, err)
					}()
					n, err := io.Copy(tconn, csStream)
					log.Infof("send %v bytes to %v, message:%v", n, addr, err)
				}(stream)

			}
		}(sess)
	}
}

func (ss *Easyss) tcpServer() {
	addr := ":" + strconv.Itoa(ss.config.ServerPort)
	ln, err := net.Listen("tcp", addr)
	if err != nil {
		log.Fatal(err)
	}
	log.Infof("starting remote socks5 server at %v ...", addr)

	for {
		conn, err := ln.Accept()
		if err != nil {
			log.Error("accept:", err)
			continue
		}
		log.Infof("a new connection(ip) is accepted. remote addr:%v", conn.RemoteAddr())

		conn.(*net.TCPConn).SetKeepAlive(true)
		conn.(*net.TCPConn).SetKeepAlivePeriod(30 * time.Second)

		go func() {
			defer conn.Close()
			for {
				addr, ciphermethod, err := handShake(conn, ss.config.Password)
				if err != nil {
					log.Warnf("get target addr err:%+v", err)
					return
				}
				if addr.String() == "" || ciphermethod == "" {
					log.Errorf("after handshake with client, but get empty addr:%v or ciphermethod:%v",
						addr.String(), ciphermethod)
					return
				}
				log.Infof("target proxy addr is:%v", addr.String())

				tconn, err := net.Dial("tcp", addr.String())
				if err != nil {
					log.Errorf("net.Dial %v err:%v", addr, err)
					return
				}

				csStream, err := cipherstream.New(conn, ss.config.Password, ciphermethod)
				if err != nil {
					log.Errorf("new cipherstream err:%+v, password:%v, method:%v",
						err, ss.config.Password, ss.config.Method)
					return
				}

				n1, n2, needclose := relay(csStream, tconn, false)
				log.Infof("send %v bytes to %v, and recive %v bytes, needclose:%v", n2, addr, n1, needclose)

				tconn.Close()
				if needclose {
					log.Infof("maybe underline connection have been closed, need close the proxy conn")
					break
				}
				log.Infof("underline connection is health, so reuse it")
			}
		}()
	}
}

func handShake(stream io.ReadWriter, password string) (addr socks.Addr, ciphermethod string, err error) {
	gcm, err := cipherstream.NewAes256GCM([]byte(password))
	if err != nil {
		return
	}

	headerbuf := make([]byte, 9+gcm.NonceSize()+gcm.Overhead())
	if _, err = io.ReadFull(stream, headerbuf); err != nil {
		err = errors.WithStack(err)
		return
	}

	headerplain, err := gcm.Decrypt(headerbuf)
	if err != nil {
		log.Errorf("gcm.Decrypt decrypt headerbuf:%v, err:%+v", headerbuf, err)
		return
	}

	payloadlen := int(headerplain[0])<<16 | int(headerplain[1])<<8 | int(headerplain[2])
	if headerplain[3] != 0x0 || headerplain[4] != 0x0 {
		err = errors.New(fmt.Sprintf("http2 data frame type:%v is invalid or flag:%v is invalid, both should be 0x0",
			headerplain[3], headerplain[4]))
		return
	}

	payloadbuf := make([]byte, payloadlen+gcm.NonceSize()+gcm.Overhead())
	if _, err = io.ReadFull(stream, payloadbuf); err != nil {
		err = errors.WithStack(err)
		log.Warnf("io.ReadFull read payloadbuf err:%+v, len:%v", err, len(payloadbuf))
		return
	}

	payloadplain, err := gcm.Decrypt(payloadbuf)
	if err != nil {
		log.Errorf("gcm.Decrypt decrypt payloadbuf:%v, err:%+v", payloadbuf, err)
		return
	}
	length := len(payloadplain)
	if length <= 1 {
		err = errors.New("handshake: payload length is invalid")
		return
	}
	ciphermethod = DecodeCipherMethod(payloadplain[length-1])

	return payloadplain[:length-1], ciphermethod, nil
}

func DecodeCipherMethod(b byte) string {
	methodMap := map[byte]string{
		1: "aes-256-gcm",
		2: "chacha20-poly1305",
	}
	if m, ok := methodMap[b]; ok {
		return m
	}
	return ""
}

// Setup a bare-bones TLS config for the server
func generateTLSConfig() *tls.Config {
	key, err := rsa.GenerateKey(rand.Reader, 1024)
	if err != nil {
		panic(err)
	}
	template := x509.Certificate{SerialNumber: big.NewInt(1)}
	certDER, err := x509.CreateCertificate(rand.Reader, &template, &template, &key.PublicKey, key)
	if err != nil {
		panic(err)
	}
	keyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})
	certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER})

	tlsCert, err := tls.X509KeyPair(certPEM, keyPEM)
	if err != nil {
		panic(err)
	}
	return &tls.Config{Certificates: []tls.Certificate{tlsCert}}
}
<commit_msg>update keepalive to 10 second<commit_after>package main

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/tls"
	"crypto/x509"
	"encoding/pem"
	"fmt"
	"io"
	"math/big"
	"net"
	"strconv"
	"time"

	quic "github.com/lucas-clemente/quic-go"
	"github.com/nange/easyss/cipherstream"
	"github.com/nange/easyss/socks"
	"github.com/pkg/errors"
	log "github.com/sirupsen/logrus"
)

func (ss *Easyss) Remote() {
	if ss.config.EnableQuic {
		ss.quicServer()
	} else {
		ss.tcpServer()
	}
}

func (ss *Easyss) quicServer() {
	addr := ":" + strconv.Itoa(ss.config.ServerPort)
	ln, err := quic.ListenAddr(addr, generateTLSConfig(), &quic.Config{IdleTimeout: time.Minute})
	if err != nil {
		log.Fatal(err)
	}
	log.Infof("starting remote quic server at %v ...", addr)

	for {
		sess, err := ln.Accept()
		if err != nil {
			log.Error("accept:", err)
			continue
		}
		log.Infof("a new session(ip) is accepted. remote addr:%v\n", sess.RemoteAddr())

		go func(sess quic.Session) {
			for {
				stream, err := sess.AcceptStream()
				if err != nil {
					log.Warnf("session accept stream err, remote addr:%v, message: %+v\n",
						sess.RemoteAddr(), errors.WithStack(err))
					sess.Close(err)
					return
				}

				go func(stream quic.Stream) {
					defer stream.Close()
					log.Infof("a new stream is accepted. stream id:%v\n", stream.StreamID())

					addr, ciphermethod, err := handShake(stream, ss.config.Password)
					if err != nil {
						log.Warnf("get target addr err:%+v", err)
						return
					}
					if addr.String() == "" || ciphermethod == "" {
						log.Errorf("after handshake with client, but get empty addr:%v or ciphermethod:%v",
							addr.String(), ciphermethod)
						return
					}
					log.Infof("target proxy addr is:%v", addr.String())

					tconn, err := net.Dial("tcp", addr.String())
					if err != nil {
						log.Errorf("net.Dial %v err:%v", addr, err)
						return
					}
					defer tconn.Close()

					csStream, err := cipherstream.New(stream, ss.config.Password, ciphermethod)
					if err != nil {
						log.Errorf("new cipherstream err:%+v, password:%v, method:%v",
							err, ss.config.Password, ss.config.Method)
						return
					}

					go func() {
						defer stream.Close()
						defer tconn.Close()
						n, err := io.Copy(csStream, tconn)
						log.Infof("reciveve %v bytes from %v, message:%v", n, addr, err)
					}()
					n, err := io.Copy(tconn, csStream)
					log.Infof("send %v bytes to %v, message:%v", n, addr, err)
				}(stream)

			}
		}(sess)
	}
}

func (ss *Easyss) tcpServer() {
	addr := ":" + strconv.Itoa(ss.config.ServerPort)
	ln, err := net.Listen("tcp", addr)
	if err != nil {
		log.Fatal(err)
	}
	log.Infof("starting remote socks5 server at %v ...", addr)

	for {
		conn, err := ln.Accept()
		if err != nil {
			log.Error("accept:", err)
			continue
		}
		log.Infof("a new connection(ip) is accepted. remote addr:%v", conn.RemoteAddr())

		conn.(*net.TCPConn).SetKeepAlive(true)
		conn.(*net.TCPConn).SetKeepAlivePeriod(10 * time.Second)

		go func() {
			defer conn.Close()
			for {
				addr, ciphermethod, err := handShake(conn, ss.config.Password)
				if err != nil {
					log.Warnf("get target addr err:%+v", err)
					return
				}
				if addr.String() == "" || ciphermethod == "" {
					log.Errorf("after handshake with client, but get empty addr:%v or ciphermethod:%v",
						addr.String(), ciphermethod)
					return
				}
				log.Infof("target proxy addr is:%v", addr.String())

				tconn, err := net.Dial("tcp", addr.String())
				if err != nil {
					log.Errorf("net.Dial %v err:%v", addr, err)
					return
				}

				csStream, err := cipherstream.New(conn, ss.config.Password, ciphermethod)
				if err != nil {
					log.Errorf("new cipherstream err:%+v, password:%v, method:%v",
						err, ss.config.Password, ss.config.Method)
					return
				}

				n1, n2, needclose := relay(csStream, tconn, false)
				log.Infof("send %v bytes to %v, and recive %v bytes, needclose:%v", n2, addr, n1, needclose)

				tconn.Close()
				if needclose {
					log.Infof("maybe underline connection have been closed, need close the proxy conn")
					break
				}
				log.Infof("underline connection is health, so reuse it")
			}
		}()
	}
}

func handShake(stream io.ReadWriter, password string) (addr socks.Addr, ciphermethod string, err error) {
	gcm, err := cipherstream.NewAes256GCM([]byte(password))
	if err != nil {
		return
	}

	headerbuf := make([]byte, 9+gcm.NonceSize()+gcm.Overhead())
	if _, err = io.ReadFull(stream, headerbuf); err != nil {
		err = errors.WithStack(err)
		return
	}

	headerplain, err := gcm.Decrypt(headerbuf)
	if err != nil {
		log.Errorf("gcm.Decrypt decrypt headerbuf:%v, err:%+v", headerbuf, err)
		return
	}

	payloadlen := int(headerplain[0])<<16 | int(headerplain[1])<<8 | int(headerplain[2])
	if headerplain[3] != 0x0 || headerplain[4] != 0x0 {
		err = errors.New(fmt.Sprintf("http2 data frame type:%v is invalid or flag:%v is invalid, both should be 0x0",
			headerplain[3], headerplain[4]))
		return
	}

	payloadbuf := make([]byte, payloadlen+gcm.NonceSize()+gcm.Overhead())
	if _, err = io.ReadFull(stream, payloadbuf); err != nil {
		err = errors.WithStack(err)
		log.Warnf("io.ReadFull read payloadbuf err:%+v, len:%v", err, len(payloadbuf))
		return
	}

	payloadplain, err := gcm.Decrypt(payloadbuf)
	if err != nil {
		log.Errorf("gcm.Decrypt decrypt payloadbuf:%v, err:%+v", payloadbuf, err)
		return
	}
	length := len(payloadplain)
	if length <= 1 {
		err = errors.New("handshake: payload length is invalid")
		return
	}
	ciphermethod = DecodeCipherMethod(payloadplain[length-1])

	return payloadplain[:length-1], ciphermethod, nil
}

func DecodeCipherMethod(b byte) string {
	methodMap := map[byte]string{
		1: "aes-256-gcm",
		2: "chacha20-poly1305",
	}
	if m, ok := methodMap[b]; ok {
		return m
	}
	return ""
}

// Setup a bare-bones TLS config for the server
func generateTLSConfig() *tls.Config {
	key, err := rsa.GenerateKey(rand.Reader, 1024)
	if err != nil {
		panic(err)
	}
	template := x509.Certificate{SerialNumber: big.NewInt(1)}
	certDER, err := x509.CreateCertificate(rand.Reader, &template, &template, &key.PublicKey, key)
	if err != nil {
		panic(err)
	}
	keyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})
	certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER})

	tlsCert, err := tls.X509KeyPair(certPEM, keyPEM)
	if err != nil {
		panic(err)
	}
	return &tls.Config{Certificates: []tls.Certificate{tlsCert}}
}
<|endoftext|>


<commit_before>package caspercloud

import (
	"encoding/json"
	"fmt"
	"github.com/BigTong/gocounter"
	"log"
	"net/http"
	"net/url"
	"runtime/debug"
)

const (
	kInternalErrorResut = "server get internal result"
)

type CasperServer struct {
	cmdCache   *CommandCache
	ct         *gocounter.Counter
	cmdFactory CommandFactory
}

func NewCasperServer(cf CommandFactory) *CasperServer {
	return &CasperServer{
		cmdCache:   NewCommandCache(),
		ct:         gocounter.NewCounter(),
		cmdFactory: cf,
	}
}

func (self *CasperServer) setArgs(cmd Command, params url.Values) *Output {
	args := self.getArgs(params)
	log.Println("setArgs:", args)
	cmd.SetInputArgs(args)

	if message := cmd.GetMessage(); message != nil {
		return message
	}
	return nil
}

func (self *CasperServer) getArgs(params url.Values) map[string]string {
	args := make(map[string]string)
	for k, v := range params {
		args[k] = v[0]
	}
	return args
}

func (self *CasperServer) Process(params url.Values) *Output {
	log.Println(params.Encode())
	id := params.Get("id")
	if len(id) == 0 {
		c := self.cmdFactory.CreateCommand(params)
		if c == nil {
			return &Output{Status: FAIL}
		}
		self.cmdCache.SetCommand(c)
		params.Set("id", c.GetId())
		return self.setArgs(c, params)
	}

	log.Println("get id", id)
	c := self.cmdCache.GetCommand(id)
	if c == nil {
		return &Output{Status: FAIL}
	}

	log.Println("get cmd", id)
	ret := self.setArgs(c, params)

	if c.Finished() {
		c.Successed()
		self.cmdCache.Delete(id)
		return &Output{Status: FINISH_ALL}
	}

	return ret
}

func (self *CasperServer) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	defer func() {
		if r := recover(); r != nil {
			log.Println("ERROR: http submit", r)
			debug.PrintStack()
		}
	}()
	self.ct.Incr("request", 1)
	params := req.URL.Query()
	ret := self.Process(params)
	output, _ := json.Marshal(ret)
	fmt.Fprint(w, string(output))
	return

}
<commit_msg>call fun when fail<commit_after>package caspercloud

import (
	"encoding/json"
	"fmt"
	"github.com/BigTong/gocounter"
	"log"
	"net/http"
	"net/url"
	"runtime/debug"
)

const (
	kInternalErrorResut = "server get internal result"
)

type CasperServer struct {
	cmdCache   *CommandCache
	ct         *gocounter.Counter
	cmdFactory CommandFactory
}

func NewCasperServer(cf CommandFactory) *CasperServer {
	return &CasperServer{
		cmdCache:   NewCommandCache(),
		ct:         gocounter.NewCounter(),
		cmdFactory: cf,
	}
}

func (self *CasperServer) setArgs(cmd Command, params url.Values) *Output {
	args := self.getArgs(params)
	log.Println("setArgs:", args)
	cmd.SetInputArgs(args)

	if message := cmd.GetMessage(); message != nil {
		return message
	}
	return nil
}

func (self *CasperServer) getArgs(params url.Values) map[string]string {
	args := make(map[string]string)
	for k, v := range params {
		args[k] = v[0]
	}
	return args
}

func (self *CasperServer) Process(params url.Values) *Output {
	log.Println(params.Encode())
	id := params.Get("id")
	if len(id) == 0 {
		c := self.cmdFactory.CreateCommand(params)
		if c == nil {
			return &Output{Status: FAIL}
		}
		self.cmdCache.SetCommand(c)
		params.Set("id", c.GetId())
		return self.setArgs(c, params)
	}

	log.Println("get id", id)
	c := self.cmdCache.GetCommand(id)
	if c == nil {
		return &Output{Status: FAIL}
	}

	log.Println("get cmd", id)
	ret := self.setArgs(c, params)

	if c.Finished() {
		c.Successed()
		self.cmdCache.Delete(id)
		return &Output{Status: FINISH_ALL}
	}

	if ret.Status == FAIL {
		c.Successed()
		return &Output{Status: FINISH_ALL}
	}

	return ret
}

func (self *CasperServer) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	defer func() {
		if r := recover(); r != nil {
			log.Println("ERROR: http submit", r)
			debug.PrintStack()
		}
	}()
	self.ct.Incr("request", 1)
	params := req.URL.Query()
	ret := self.Process(params)
	output, _ := json.Marshal(ret)
	fmt.Fprint(w, string(output))
	return

}
<|endoftext|>


<commit_before>package main

import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    s := r.URL.Path[1:]
    fmt.Printf("Just about to send output -[%v]\n", s)
    fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}
<commit_msg>Using John's source instead.<commit_after>package main

import (
	"flag"
	"fmt"
	"log"
	"net/http"
	"strings"
	"time"
	"unsafe"
)

var verbose = flag.Bool("v", true, "")

func noun(n int) string {
	if n == 1 {
		return "bottle"
	}
	return "bottles"
}

func nobottles() string {
	kitchenSink()
	nomore := fmt.Sprintf("No more %s of beer on the wall!", noun(0))
	return nomore
}
func bottles(n int, song []string) (r []string) {
	var line string
	if n <= 0 {
		line = nobottles()
		song = append(song, line)
		r = song
	} else {
		line = fmt.Sprintf("%d %s of beer on the wall!", n, noun(n))
		song = append(song, line)
		r = bottles(n-1, song)
	}
	fmt.Printf("%s","")
	return r
}

func Beer(w http.ResponseWriter, r *http.Request) {
	if *verbose {
		log.Println("beer request")
	}
	song := bottles(10, nil)
	fmt.Fprintln(w, "\n")
	fmt.Fprintln(w, strings.Join(song, "
"))
	fmt.Fprintln(w, "\n")
}

func main() {
	flag.Parse()
	http.HandleFunc("/bar", Beer)
	log.Fatal(http.ListenAndServe(":8080", nil))
}

type FooInterface interface {
	Bar()
}

type FooStruct struct {
	a int
	b string
}

func (f *FooStruct) Bar() {}

type myInt int

func kitchenSink() {
	var (
		Z_bool_false          bool        = false
		Z_bool_true           bool        = true
		Z_int                 int         = -21
		Z_int8                int8        = -121
		Z_int16               int16       = -32321
		Z_int32               int32       = -1987654321
		Z_int64               int64       = -9012345678987654321
		Z_uint                uint        = 21
		Z_uint8               uint8       = 231
		Z_uint16              uint16      = 54321
		Z_uint32              uint32      = 3217654321
		Z_uint64              uint64      = 12345678900987654321
		Z_uintptr             uintptr     = 21
		Z_float32             float32     = 1.54321
		Z_float64             float64     = 1.987654321
		Z_complex64           complex64   = 1.54321 + 2.54321i
		Z_complex128          complex128  = 1.987654321 - 2.987654321i
		Z_array               [5]int8     = [5]int8{-121, 121, 3, 2, 1}
		Z_array_temp          [5]int8     = [5]int8{-121, 121, 3, 2, 1}
		Z_array_empty         [0]int8     = [0]int8{}
		Z_array_of_empties    [2]struct{} = [2]struct{}{struct{}{}, struct{}{}}
		Z_channel             chan int    = make(chan int)
		Z_channel_buffered    chan int    = make(chan int, 10)
		Z_channel_nil         chan int
		Z_func_bar                              = (*FooStruct).Bar
		Z_func_int8_r_int8                      = func(x int8) int8 { return x + 1 }
		Z_func_int8_r_pint8                     = func(x int8) *int8 { y := x + 1; return &y }
		Z_func_copy                             = Z_func_int8_r_int8
		Z_func_nil            func(x int8) int8 = nil
		Z_struct              FooStruct         = FooStruct{a: 21, b: "hi"}
		Z_struct_temp         FooStruct         = FooStruct{a: 21, b: "hi"}
		Z_pointer             *FooStruct        = &Z_struct_temp
		Z_pointer_nil         *FooStruct
		Z_interface           FooInterface = &Z_struct_temp
		Z_interface_typed_nil FooInterface = Z_pointer_nil
		Z_interface_nil       FooInterface
		Z_map                 map[int8]float32 = map[int8]float32{-21: 3.54321}
		Z_map_2               map[int16]int8   = map[int16]int8{1024: 1}
		Z_map_empty           map[int8]float32 = map[int8]float32{}
		Z_map_nil             map[int8]float32
		Z_slice               []byte = []byte{'s', 'l', 'i', 'c', 'e'}
		Z_slice_2             []int8 = Z_array_temp[0:2]
		Z_slice_nil           []byte
		Z_string              string         = "I'm a string"
		Z_uint_temp           uint           = 21
		Z_unsafe_pointer      unsafe.Pointer = unsafe.Pointer(&Z_uint_temp)
		Z_unsafe_pointer_nil  unsafe.Pointer
		Z_byte                byte  = 111
		Z_rune                rune  = '~'
		Z_int_typedef         myInt = 42
	)
	for i := 0; i < 10; i++ {
		maybePrintln(Z_bool_false, Z_bool_true)
		maybePrintln(Z_int, Z_int8, Z_int16, Z_int32, Z_int64)
		maybePrintln(Z_uint, Z_uint8, Z_uint16, Z_uint32, Z_uint64, Z_uintptr)
		maybePrintln(Z_float32, Z_float64, Z_complex64, Z_complex128)
		maybePrintln(Z_array, Z_array_empty, Z_array_of_empties)
		maybePrintln(Z_channel, Z_channel_buffered, Z_channel_nil)
		maybePrintln(Z_func_bar, Z_func_int8_r_int8, Z_func_int8_r_pint8)
		maybePrintln(Z_interface, Z_interface_nil, Z_interface_typed_nil)
		maybePrintln(Z_map, Z_map_2, Z_map_empty, Z_map_nil)
		maybePrintln(Z_pointer, Z_pointer_nil)
		maybePrintln(Z_slice, Z_slice_2, Z_slice_nil)
		maybePrintln(Z_string, Z_struct)
		maybePrintln(Z_unsafe_pointer, Z_unsafe_pointer_nil)
		maybePrintln(Z_func_copy, Z_func_nil, Z_byte, Z_rune, Z_int_typedef)
	}
}

// maybePrintln won't print anything.  We just don't want the compiler to optimize it away.
func maybePrintln(v ...interface{}) {
	var t time.Time
	if time.Now() == t {
		fmt.Println(v...)
	}
}

// This is another version of the file.
<|endoftext|>


<commit_before>// Package server is a wrapper around the stdlib http server and x/autocert pkg.
package server

import (
	"crypto/tls"
	"fmt"
	"log"
	"net/http"
	"os"
	"strings"
	"time"

	"golang.org/x/crypto/acme/autocert"
)

// Server wraps the stdlib http server and x/autocert pkg with some setup.
type Server struct {

	// Which port to serve on - in 2.0 pass as argument for New()
	port int

	// Which mode we're in, read from ENV variable
	// Deprecated - due to be removed in 2.0
	production bool

	// Deprecated Logging - due to be removed in 2.0
	// Instead use the structured logging with server/log
	Logger Logger

	// Deprecated configs will be removed from the server object in 2.0
	// Use server/config instead to read the config from app.
	// Server configs - access with Config(string)
	configProduction  map[string]string
	configDevelopment map[string]string
	configTest        map[string]string
}

// New creates a new server instance
func New() (*Server, error) {

	// Check environment variable to see if we are in production mode
	prod := false
	if os.Getenv("FRAG_ENV") == "production" {
		prod = true
	}

	// Set up a new server
	s := &Server{
		port:              3000,
		production:        prod,
		configProduction:  make(map[string]string),
		configDevelopment: make(map[string]string),
		configTest:        make(map[string]string),
		Logger:            log.New(os.Stderr, "fragmenta: ", log.LstdFlags),
	}

	// Old style config read - this will be going away in Fragmenta 2.0
	// use server/config instead from the app
	err := s.readConfig()
	if err != nil {
		return s, err
	}
	err = s.readArguments()
	if err != nil {
		return s, err
	}

	return s, err
}

// Port returns the port of the server
func (s *Server) Port() int {
	return s.port
}

// PortString returns a string port suitable for passing to http.Server
func (s *Server) PortString() string {
	return fmt.Sprintf(":%d", s.port)
}

// Start starts an http server on the given port
func (s *Server) Start() error {
	server := &http.Server{
		Addr:         s.PortString(),
		ReadTimeout:  30 * time.Second,
		WriteTimeout: 60 * time.Second,
	}
	return server.ListenAndServe()
}

// StartTLS starts an https server on the given port
// with tls cert/key from config keys.
func (s *Server) StartTLS(cert, key string) error {

	// Set up a new http server
	server := &http.Server{
		// Set the port in the preferred string format
		Addr: s.PortString(),
	}

	return server.ListenAndServeTLS(cert, key)
}

// StartTLSAutocert starts an https server on the given port
// by requesting certs from an ACME provider.
// The server must be on a public IP which matches the
// DNS for the domains.
func (s *Server) StartTLSAutocert(email string, domains string) error {
	autocertDomains := strings.Split(domains, " ")
	certManager := &autocert.Manager{
		Prompt:     autocert.AcceptTOS,
		Email:      email,                                      // Email for problems with certs
		HostPolicy: autocert.HostWhitelist(autocertDomains...), // Domains to request certs for
		Cache:      autocert.DirCache("secrets"),               // Cache certs in secrets folder
	}
	server := s.ConfiguredTLSServer(certManager)
	return server.ListenAndServeTLS("", "")
}

// ConfiguredTLSServer returns a TLS server instance with a secure config
// this server has read/write timeouts set to 20 seconds,
// prefers server cipher suites and only uses certain accelerated curves
// see - https://blog.gopheracademy.com/advent-2016/exposing-go-on-the-internet/
func (s *Server) ConfiguredTLSServer(certManager *autocert.Manager) *http.Server {

	return &http.Server{
		// Set the port in the preferred string format
		Addr: s.PortString(),

		// The default server from net/http has no timeouts
		ReadTimeout:  30 * time.Second,
		WriteTimeout: 60 * time.Second,
		//	IdleTimeout:  120 * time.Second,

		// This TLS config follows recommendations in the above article
		TLSConfig: &tls.Config{
			// Pass in a cert manager if you want one set
			// this will only be used if the server Certificates are empty
			GetCertificate: certManager.GetCertificate,

			// VersionTLS11 or VersionTLS12 would exclude many browsers
			// inc. Android 4.x, IE 10, Opera 12.17, Safari 6
			// So unfortunately not acceptable as a default yet
			// Current default here for clarity
			MinVersion: tls.VersionTLS10,

			// Causes servers to use Go's default ciphersuite preferences,
			// which are tuned to avoid attacks. Does nothing on clients.
			PreferServerCipherSuites: true,
			// Only use curves which have assembly implementations
			CurvePreferences: []tls.CurveID{
				tls.CurveP256,
				//	tls.X25519, // Go 1.8 only
			},
		},
	}

}

// StartRedirectAll starts redirecting from port given to the given url
// this should be called before StartTLS if redirecting to https
func (s *Server) StartRedirectAll(p int, url string) {
	port := fmt.Sprintf(":%d", p)
	// Listen and server on port p in a separate goroutine
	go func() {
		http.ListenAndServe(port, &redirectHandler{redirect: url})
	}()
}

// redirectHandler is useful if serving tls direct (not behind a proxy)
// and a redirect from port 80 is required.
type redirectHandler struct {
	redirect string
}

// ServeHTTP on this handler simply redirects to the main site
func (m *redirectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	http.Redirect(w, r, m.redirect, http.StatusMovedPermanently)
}
<commit_msg>Fix StartRedirectAll to redirect to full path at new host - fixes #4<commit_after>// Package server is a wrapper around the stdlib http server and x/autocert pkg.
package server

import (
	"crypto/tls"
	"fmt"
	"log"
	"net/http"
	"os"
	"strings"
	"time"

	"golang.org/x/crypto/acme/autocert"
)

// Server wraps the stdlib http server and x/autocert pkg with some setup.
type Server struct {

	// Which port to serve on - in 2.0 pass as argument for New()
	port int

	// Which mode we're in, read from ENV variable
	// Deprecated - due to be removed in 2.0
	production bool

	// Deprecated Logging - due to be removed in 2.0
	// Instead use the structured logging with server/log
	Logger Logger

	// Deprecated configs will be removed from the server object in 2.0
	// Use server/config instead to read the config from app.
	// Server configs - access with Config(string)
	configProduction  map[string]string
	configDevelopment map[string]string
	configTest        map[string]string
}

// New creates a new server instance
func New() (*Server, error) {

	// Check environment variable to see if we are in production mode
	prod := false
	if os.Getenv("FRAG_ENV") == "production" {
		prod = true
	}

	// Set up a new server
	s := &Server{
		port:              3000,
		production:        prod,
		configProduction:  make(map[string]string),
		configDevelopment: make(map[string]string),
		configTest:        make(map[string]string),
		Logger:            log.New(os.Stderr, "fragmenta: ", log.LstdFlags),
	}

	// Old style config read - this will be going away in Fragmenta 2.0
	// use server/config instead from the app
	err := s.readConfig()
	if err != nil {
		return s, err
	}
	err = s.readArguments()
	if err != nil {
		return s, err
	}

	return s, err
}

// Port returns the port of the server
func (s *Server) Port() int {
	return s.port
}

// PortString returns a string port suitable for passing to http.Server
func (s *Server) PortString() string {
	return fmt.Sprintf(":%d", s.port)
}

// Start starts an http server on the given port
func (s *Server) Start() error {
	server := &http.Server{
		Addr:         s.PortString(),
		ReadTimeout:  30 * time.Second,
		WriteTimeout: 60 * time.Second,
	}
	return server.ListenAndServe()
}

// StartTLS starts an https server on the given port
// with tls cert/key from config keys.
func (s *Server) StartTLS(cert, key string) error {

	// Set up a new http server
	server := &http.Server{
		// Set the port in the preferred string format
		Addr: s.PortString(),
	}

	return server.ListenAndServeTLS(cert, key)
}

// StartTLSAutocert starts an https server on the given port
// by requesting certs from an ACME provider.
// The server must be on a public IP which matches the
// DNS for the domains.
func (s *Server) StartTLSAutocert(email string, domains string) error {
	autocertDomains := strings.Split(domains, " ")
	certManager := &autocert.Manager{
		Prompt:     autocert.AcceptTOS,
		Email:      email,                                      // Email for problems with certs
		HostPolicy: autocert.HostWhitelist(autocertDomains...), // Domains to request certs for
		Cache:      autocert.DirCache("secrets"),               // Cache certs in secrets folder
	}
	server := s.ConfiguredTLSServer(certManager)
	return server.ListenAndServeTLS("", "")
}

// ConfiguredTLSServer returns a TLS server instance with a secure config
// this server has read/write timeouts set to 20 seconds,
// prefers server cipher suites and only uses certain accelerated curves
// see - https://blog.gopheracademy.com/advent-2016/exposing-go-on-the-internet/
func (s *Server) ConfiguredTLSServer(certManager *autocert.Manager) *http.Server {

	return &http.Server{
		// Set the port in the preferred string format
		Addr: s.PortString(),

		// The default server from net/http has no timeouts
		ReadTimeout:  30 * time.Second,
		WriteTimeout: 60 * time.Second,
		//	IdleTimeout:  120 * time.Second,

		// This TLS config follows recommendations in the above article
		TLSConfig: &tls.Config{
			// Pass in a cert manager if you want one set
			// this will only be used if the server Certificates are empty
			GetCertificate: certManager.GetCertificate,

			// VersionTLS11 or VersionTLS12 would exclude many browsers
			// inc. Android 4.x, IE 10, Opera 12.17, Safari 6
			// So unfortunately not acceptable as a default yet
			// Current default here for clarity
			MinVersion: tls.VersionTLS10,

			// Causes servers to use Go's default ciphersuite preferences,
			// which are tuned to avoid attacks. Does nothing on clients.
			PreferServerCipherSuites: true,
			// Only use curves which have assembly implementations
			CurvePreferences: []tls.CurveID{
				tls.CurveP256,
				//	tls.X25519, // Go 1.8 only
			},
		},
	}

}

// StartRedirectAll starts redirecting all requests on the given port to the given host
// this should be called before StartTLS if redirecting http on port 80 to https
func (s *Server) StartRedirectAll(p int, host string) {
	port := fmt.Sprintf(":%d", p)
	// Listen and server on port p in a separate goroutine
	go func() {
		http.ListenAndServe(port, &redirectHandler{host: host})
	}()
}

// redirectHandler is useful if serving tls direct (not behind a proxy)
// and a redirect from port 80 is required.
type redirectHandler struct {
	host string
}

// ServeHTTP on this handler simply redirects to the main site
func (m *redirectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	http.Redirect(w, r, m.host+r.URL.String(), http.StatusMovedPermanently)
}
<|endoftext|>


<commit_before>// Copyright 2016-2021 terraform-provider-sakuracloud authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package sakuracloud

import (
	"testing"

	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
)

func TestAccSakuraCloudDataSourceCDROM_basic(t *testing.T) {
	resourceName := "data.sakuracloud_cdrom.foobar"
	resource.ParallelTest(t, resource.TestCase{
		PreCheck:          func() { testAccPreCheck(t) },
		ProviderFactories: testAccProviderFactories,
		Steps: []resource.TestStep{
			{
				Config: testAccSakuraCloudDataSourceCDROM_basic,
				Check: resource.ComposeTestCheckFunc(
					testCheckSakuraCloudDataSourceExists(resourceName),
					resource.TestCheckResourceAttr(resourceName, "name", "Parted Magic 2013_08_01"),
					resource.TestCheckResourceAttr(resourceName, "size", "5"),
					resource.TestCheckResourceAttr(resourceName, "tags.#", "5"),
					resource.TestCheckResourceAttr(resourceName, "tags.0", "arch-64bit"),
					resource.TestCheckResourceAttr(resourceName, "tags.1", "current-stable"),
					resource.TestCheckResourceAttr(resourceName, "tags.2", "distro-parted_magic"),
					resource.TestCheckResourceAttr(resourceName, "tags.3", "distro-ver-2013.08.01"),
					resource.TestCheckResourceAttr(resourceName, "tags.4", "os-linux"),
				),
			},
		},
	})
}

var testAccSakuraCloudDataSourceCDROM_basic = `
data "sakuracloud_cdrom" "foobar" {
  filter {
    condition {
	  name    = "Name"
	  values = ["Parted Magic 2013_08_01"]
    }
  }
}`
<commit_msg>fix broken test - TestAccSakuraCloudDataSourceCDROM_basic<commit_after>// Copyright 2016-2021 terraform-provider-sakuracloud authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package sakuracloud

import (
	"testing"

	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
)

func TestAccSakuraCloudDataSourceCDROM_basic(t *testing.T) {
	skipIfFakeModeEnabled(t)

	resourceName := "data.sakuracloud_cdrom.foobar"
	rand := randomName()

	resource.ParallelTest(t, resource.TestCase{
		PreCheck:          func() { testAccPreCheck(t) },
		ProviderFactories: testAccProviderFactories,
		Steps: []resource.TestStep{
			{
				Config: buildConfigWithArgs(testAccSakuraCloudDataSourceCDROM_basic, rand),
				Check: resource.ComposeTestCheckFunc(
					testCheckSakuraCloudDataSourceExists(resourceName),
					resource.TestCheckResourceAttr(resourceName, "name", rand),
					resource.TestCheckResourceAttr(resourceName, "description", "description"),
					resource.TestCheckResourceAttr(resourceName, "size", "5"),
					resource.TestCheckResourceAttr(resourceName, "tags.#", "2"),
					resource.TestCheckResourceAttr(resourceName, "tags.0", "tag1"),
					resource.TestCheckResourceAttr(resourceName, "tags.1", "tag2"),
				),
			},
		},
	})
}

var testAccSakuraCloudDataSourceCDROM_basic = `
resource "sakuracloud_cdrom" "foobar" {
  name           = "{{ .arg0 }}"
  size           = 5
  iso_image_file = "test/dummy.iso"
  description    = "description"
  tags           = ["tag1", "tag2"]
}

data "sakuracloud_cdrom" "foobar" {
  filter {
    condition {
	  name    = "Name"
	  values = [sakuracloud_cdrom.foobar.name]
    }
  }
}`
<|endoftext|>


<commit_before>// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package httputil

import (
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
	"testing"
)

type dumpTest struct {
	Req  http.Request
	Body interface{} // optional []byte or func() io.ReadCloser to populate Req.Body

	WantDump    string
	WantDumpOut string
}

var dumpTests = []dumpTest{

	// HTTP/1.1 => chunked coding; body; empty trailer
	{
		Req: http.Request{
			Method: "GET",
			URL: &url.URL{
				Scheme: "http",
				Host:   "www.google.com",
				Path:   "/search",
			},
			ProtoMajor:       1,
			ProtoMinor:       1,
			TransferEncoding: []string{"chunked"},
		},

		Body: []byte("abcdef"),

		WantDump: "GET /search HTTP/1.1\r\n" +
			"Host: www.google.com\r\n" +
			"Transfer-Encoding: chunked\r\n\r\n" +
			chunk("abcdef") + chunk(""),
	},

	// Verify that DumpRequest preserves the HTTP version number, doesn't add a Host,
	// and doesn't add a User-Agent.
	{
		Req: http.Request{
			Method:     "GET",
			URL:        mustParseURL("/foo"),
			ProtoMajor: 1,
			ProtoMinor: 0,
			Header: http.Header{
				"X-Foo": []string{"X-Bar"},
			},
		},

		WantDump: "GET /foo HTTP/1.0\r\n" +
			"X-Foo: X-Bar\r\n\r\n",
	},

	{
		Req: *mustNewRequest("GET", "http://example.com/foo", nil),

		WantDumpOut: "GET /foo HTTP/1.1\r\n" +
			"Host: example.com\r\n" +
			"User-Agent: Go http package\r\n" +
			"Accept-Encoding: gzip\r\n\r\n",
	},

	// Test that an https URL doesn't try to do an SSL negotiation
	// with a bytes.Buffer and hang with all goroutines not
	// runnable.
	{
		Req: *mustNewRequest("GET", "https://example.com/foo", nil),

		WantDumpOut: "GET /foo HTTP/1.1\r\n" +
			"Host: example.com\r\n" +
			"User-Agent: Go http package\r\n" +
			"Accept-Encoding: gzip\r\n\r\n",
	},
}

func TestDumpRequest(t *testing.T) {
	for i, tt := range dumpTests {
		setBody := func() {
			if tt.Body == nil {
				return
			}
			switch b := tt.Body.(type) {
			case []byte:
				tt.Req.Body = ioutil.NopCloser(bytes.NewBuffer(b))
			case func() io.ReadCloser:
				tt.Req.Body = b()
			}
		}
		setBody()
		if tt.Req.Header == nil {
			tt.Req.Header = make(http.Header)
		}

		if tt.WantDump != "" {
			setBody()
			dump, err := DumpRequest(&tt.Req, true)
			if err != nil {
				t.Errorf("DumpRequest #%d: %s", i, err)
				continue
			}
			if string(dump) != tt.WantDump {
				t.Errorf("DumpRequest %d, expecting:\n%s\nGot:\n%s\n", i, tt.WantDump, string(dump))
				continue
			}
		}

		if tt.WantDumpOut != "" {
			setBody()
			dump, err := DumpRequestOut(&tt.Req, true)
			if err != nil {
				t.Errorf("DumpRequestOut #%d: %s", i, err)
				continue
			}
			if string(dump) != tt.WantDumpOut {
				t.Errorf("DumpRequestOut %d, expecting:\n%s\nGot:\n%s\n", i, tt.WantDumpOut, string(dump))
				continue
			}
		}
	}
}

func chunk(s string) string {
	return fmt.Sprintf("%x\r\n%s\r\n", len(s), s)
}

func mustParseURL(s string) *url.URL {
	u, err := url.Parse(s)
	if err != nil {
		panic(fmt.Sprintf("Error parsing URL %q: %v", s, err))
	}
	return u
}

func mustNewRequest(method, url string, body io.Reader) *http.Request {
	req, err := http.NewRequest(method, url, body)
	if err != nil {
		panic(fmt.Sprintf("NewRequest(%q, %q, %p) err = %v", method, url, body, err))
	}
	return req
}
<commit_msg>net/http/httputil: fix build<commit_after>// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package httputil

import (
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
	"testing"
)

type dumpTest struct {
	Req  http.Request
	Body interface{} // optional []byte or func() io.ReadCloser to populate Req.Body

	WantDump    string
	WantDumpOut string
}

var dumpTests = []dumpTest{

	// HTTP/1.1 => chunked coding; body; empty trailer
	{
		Req: http.Request{
			Method: "GET",
			URL: &url.URL{
				Scheme: "http",
				Host:   "www.google.com",
				Path:   "/search",
			},
			ProtoMajor:       1,
			ProtoMinor:       1,
			TransferEncoding: []string{"chunked"},
		},

		Body: []byte("abcdef"),

		WantDump: "GET /search HTTP/1.1\r\n" +
			"Host: www.google.com\r\n" +
			"Transfer-Encoding: chunked\r\n\r\n" +
			chunk("abcdef") + chunk(""),
	},

	// Verify that DumpRequest preserves the HTTP version number, doesn't add a Host,
	// and doesn't add a User-Agent.
	{
		Req: http.Request{
			Method:     "GET",
			URL:        mustParseURL("/foo"),
			ProtoMajor: 1,
			ProtoMinor: 0,
			Header: http.Header{
				"X-Foo": []string{"X-Bar"},
			},
		},

		WantDump: "GET /foo HTTP/1.0\r\n" +
			"X-Foo: X-Bar\r\n\r\n",
	},

	{
		Req: *mustNewRequest("GET", "http://example.com/foo", nil),

		WantDumpOut: "GET /foo HTTP/1.1\r\n" +
			"Host: example.com\r\n" +
			"User-Agent: Go 1.1 package http\r\n" +
			"Accept-Encoding: gzip\r\n\r\n",
	},

	// Test that an https URL doesn't try to do an SSL negotiation
	// with a bytes.Buffer and hang with all goroutines not
	// runnable.
	{
		Req: *mustNewRequest("GET", "https://example.com/foo", nil),

		WantDumpOut: "GET /foo HTTP/1.1\r\n" +
			"Host: example.com\r\n" +
			"User-Agent: Go 1.1 package http\r\n" +
			"Accept-Encoding: gzip\r\n\r\n",
	},
}

func TestDumpRequest(t *testing.T) {
	for i, tt := range dumpTests {
		setBody := func() {
			if tt.Body == nil {
				return
			}
			switch b := tt.Body.(type) {
			case []byte:
				tt.Req.Body = ioutil.NopCloser(bytes.NewBuffer(b))
			case func() io.ReadCloser:
				tt.Req.Body = b()
			}
		}
		setBody()
		if tt.Req.Header == nil {
			tt.Req.Header = make(http.Header)
		}

		if tt.WantDump != "" {
			setBody()
			dump, err := DumpRequest(&tt.Req, true)
			if err != nil {
				t.Errorf("DumpRequest #%d: %s", i, err)
				continue
			}
			if string(dump) != tt.WantDump {
				t.Errorf("DumpRequest %d, expecting:\n%s\nGot:\n%s\n", i, tt.WantDump, string(dump))
				continue
			}
		}

		if tt.WantDumpOut != "" {
			setBody()
			dump, err := DumpRequestOut(&tt.Req, true)
			if err != nil {
				t.Errorf("DumpRequestOut #%d: %s", i, err)
				continue
			}
			if string(dump) != tt.WantDumpOut {
				t.Errorf("DumpRequestOut %d, expecting:\n%s\nGot:\n%s\n", i, tt.WantDumpOut, string(dump))
				continue
			}
		}
	}
}

func chunk(s string) string {
	return fmt.Sprintf("%x\r\n%s\r\n", len(s), s)
}

func mustParseURL(s string) *url.URL {
	u, err := url.Parse(s)
	if err != nil {
		panic(fmt.Sprintf("Error parsing URL %q: %v", s, err))
	}
	return u
}

func mustNewRequest(method, url string, body io.Reader) *http.Request {
	req, err := http.NewRequest(method, url, body)
	if err != nil {
		panic(fmt.Sprintf("NewRequest(%q, %q, %p) err = %v", method, url, body, err))
	}
	return req
}
<|endoftext|>


<commit_before>package vizzini_test

import (
	"flag"
	"fmt"
	"log"
	"net/url"
	"os"

	"github.com/onsi/say"
	"github.com/pivotal-golang/clock"
	"github.com/pivotal-golang/lager"
	"github.com/pivotal-golang/lager/lagertest"

	"github.com/nu7hatch/gouuid"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	"testing"
	"time"

	"github.com/cloudfoundry-incubator/bbs"
	"github.com/cloudfoundry-incubator/bbs/models"
	"github.com/cloudfoundry-incubator/consuladapter"
)

var bbsClient bbs.Client
var serviceClient bbs.ServiceClient
var domain string
var otherDomain string
var defaultRootFS string
var guid string
var startTime time.Time

var bbsAddress string
var bbsClientCert string
var bbsClientKey string
var consulAddress string
var routableDomainSuffix string
var hostAddress string
var logger lager.Logger

var timeout time.Duration
var dockerTimeout time.Duration

func init() {
	flag.StringVar(&bbsAddress, "bbs-address", "http://10.244.16.2:8889", "http address for the bbs (required)")
	flag.StringVar(&bbsClientCert, "bbs-client-cert", "", "bbs client ssl certificate")
	flag.StringVar(&bbsClientKey, "bbs-client-key", "", "bbs client ssl key")
	flag.StringVar(&consulAddress, "consul-address", "http://127.0.0.1:8500", "http address for the consul agent (required)")
	flag.StringVar(&routableDomainSuffix, "routable-domain-suffix", "bosh-lite.com", "suffix to use when constructing FQDN")
	flag.StringVar(&hostAddress, "host-address", "10.0.2.2", "address that a process running in a container on Diego can use to reach the machine running this test.  Typically the gateway on the vagrant VM.")
	flag.Parse()

	if bbsAddress == "" {
		log.Fatal("i need a bbs address to talk to Diego...")
	}

	if consulAddress == "" {
		log.Fatal("i need a consul address to talk to Diego...")
	}
}

func TestVizziniSuite(t *testing.T) {
	RegisterFailHandler(Fail)
	RunSpecs(t, "Vizzini Suite")
}

func NewGuid() string {
	u, err := uuid.NewV4()
	Ω(err).ShouldNot(HaveOccurred())
	return domain + "-" + u.String()[:8]
}

var _ = BeforeSuite(func() {
	timeout = 10 * time.Second
	dockerTimeout = 120 * time.Second

	timeoutArg := os.Getenv("DEFAULT_EVENTUALLY_TIMEOUT")
	if timeoutArg != "" {
		timeout, err := time.ParseDuration(timeoutArg)
		Ω(err).ShouldNot(HaveOccurred(), "invalid value '"+timeoutArg+"' for DEFAULT_EVENTUALLY_TIMEOUT")
		fmt.Printf("Setting Default Eventually Timeout to %s\n", timeout)
	}

	SetDefaultEventuallyTimeout(timeout)
	SetDefaultEventuallyPollingInterval(500 * time.Millisecond)
	SetDefaultConsistentlyPollingInterval(200 * time.Millisecond)
	domain = fmt.Sprintf("vizzini-%d", GinkgoParallelNode())
	otherDomain = fmt.Sprintf("vizzini-other-%d", GinkgoParallelNode())
	defaultRootFS = models.PreloadedRootFS("cflinuxfs2")

	var err error
	bbsClient = initializeBBSClient()

	consulClient, err := consuladapter.NewClient(consulAddress)
	Ω(err).ShouldNot(HaveOccurred())

	sessionMgr := consuladapter.NewSessionManager(consulClient)
	consulSession, err := consuladapter.NewSession("vizzini", 10*time.Second, consulClient, sessionMgr)
	Ω(err).ShouldNot(HaveOccurred())

	logger = lagertest.NewTestLogger("vizzini")

	serviceClient = bbs.NewServiceClient(consulSession, clock.NewClock())
})

var _ = BeforeEach(func() {
	startTime = time.Now()
	guid = NewGuid()
})

var _ = AfterEach(func() {
	defer func() {
		endTime := time.Now()
		fmt.Fprint(GinkgoWriter, say.Cyan("\n%s\nThis test referenced GUID %s\nStart time: %s (%d)\nEnd time: %s (%d)\n", CurrentGinkgoTestDescription().FullTestText, guid, startTime, startTime.Unix(), endTime, endTime.Unix()))
	}()

	for _, domain := range []string{domain, otherDomain} {
		ClearOutTasksInDomain(domain)
		ClearOutDesiredLRPsInDomain(domain)
	}
})

var _ = AfterSuite(func() {
	for _, domain := range []string{domain, otherDomain} {
		bbsClient.UpsertDomain(domain, 5*time.Minute) //leave the domain around forever so that Diego cleans up if need be
	}

	for _, domain := range []string{domain, otherDomain} {
		ClearOutDesiredLRPsInDomain(domain)
		ClearOutTasksInDomain(domain)
	}
})

func initializeBBSClient() bbs.Client {
	bbsURL, err := url.Parse(bbsAddress)
	Ω(err).ShouldNot(HaveOccurred())

	if bbsURL.Scheme != "https" {
		return bbs.NewClient(bbsAddress)
	}

	bbsClient, err := bbs.NewSecureSkipVerifyClient(bbsAddress, bbsClientCert, bbsClientKey, 0, 0)
	Ω(err).ShouldNot(HaveOccurred())
	return bbsClient
}
<commit_msg>Fix variable shadowing<commit_after>package vizzini_test

import (
	"flag"
	"fmt"
	"log"
	"net/url"
	"os"

	"github.com/onsi/say"
	"github.com/pivotal-golang/clock"
	"github.com/pivotal-golang/lager"
	"github.com/pivotal-golang/lager/lagertest"

	"github.com/nu7hatch/gouuid"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	"testing"
	"time"

	"github.com/cloudfoundry-incubator/bbs"
	"github.com/cloudfoundry-incubator/bbs/models"
	"github.com/cloudfoundry-incubator/consuladapter"
)

var bbsClient bbs.Client
var serviceClient bbs.ServiceClient
var domain string
var otherDomain string
var defaultRootFS string
var guid string
var startTime time.Time

var bbsAddress string
var bbsClientCert string
var bbsClientKey string
var consulAddress string
var routableDomainSuffix string
var hostAddress string
var logger lager.Logger

var timeout time.Duration
var dockerTimeout time.Duration

func init() {
	flag.StringVar(&bbsAddress, "bbs-address", "http://10.244.16.2:8889", "http address for the bbs (required)")
	flag.StringVar(&bbsClientCert, "bbs-client-cert", "", "bbs client ssl certificate")
	flag.StringVar(&bbsClientKey, "bbs-client-key", "", "bbs client ssl key")
	flag.StringVar(&consulAddress, "consul-address", "http://127.0.0.1:8500", "http address for the consul agent (required)")
	flag.StringVar(&routableDomainSuffix, "routable-domain-suffix", "bosh-lite.com", "suffix to use when constructing FQDN")
	flag.StringVar(&hostAddress, "host-address", "10.0.2.2", "address that a process running in a container on Diego can use to reach the machine running this test.  Typically the gateway on the vagrant VM.")
	flag.Parse()

	if bbsAddress == "" {
		log.Fatal("i need a bbs address to talk to Diego...")
	}

	if consulAddress == "" {
		log.Fatal("i need a consul address to talk to Diego...")
	}
}

func TestVizziniSuite(t *testing.T) {
	RegisterFailHandler(Fail)
	RunSpecs(t, "Vizzini Suite")
}

func NewGuid() string {
	u, err := uuid.NewV4()
	Ω(err).ShouldNot(HaveOccurred())
	return domain + "-" + u.String()[:8]
}

var _ = BeforeSuite(func() {
	var err error
	timeout = 10 * time.Second
	dockerTimeout = 120 * time.Second

	timeoutArg := os.Getenv("DEFAULT_EVENTUALLY_TIMEOUT")
	if timeoutArg != "" {
		timeout, err = time.ParseDuration(timeoutArg)
		Ω(err).ShouldNot(HaveOccurred(), "invalid value '"+timeoutArg+"' for DEFAULT_EVENTUALLY_TIMEOUT")
		fmt.Printf("Setting Default Eventually Timeout to %s\n", timeout)
	}

	SetDefaultEventuallyTimeout(timeout)
	SetDefaultEventuallyPollingInterval(500 * time.Millisecond)
	SetDefaultConsistentlyPollingInterval(200 * time.Millisecond)
	domain = fmt.Sprintf("vizzini-%d", GinkgoParallelNode())
	otherDomain = fmt.Sprintf("vizzini-other-%d", GinkgoParallelNode())
	defaultRootFS = models.PreloadedRootFS("cflinuxfs2")

	bbsClient = initializeBBSClient()

	consulClient, err := consuladapter.NewClient(consulAddress)
	Ω(err).ShouldNot(HaveOccurred())

	sessionMgr := consuladapter.NewSessionManager(consulClient)
	consulSession, err := consuladapter.NewSession("vizzini", 10*time.Second, consulClient, sessionMgr)
	Ω(err).ShouldNot(HaveOccurred())

	logger = lagertest.NewTestLogger("vizzini")

	serviceClient = bbs.NewServiceClient(consulSession, clock.NewClock())
})

var _ = BeforeEach(func() {
	startTime = time.Now()
	guid = NewGuid()
})

var _ = AfterEach(func() {
	defer func() {
		endTime := time.Now()
		fmt.Fprint(GinkgoWriter, say.Cyan("\n%s\nThis test referenced GUID %s\nStart time: %s (%d)\nEnd time: %s (%d)\n", CurrentGinkgoTestDescription().FullTestText, guid, startTime, startTime.Unix(), endTime, endTime.Unix()))
	}()

	for _, domain := range []string{domain, otherDomain} {
		ClearOutTasksInDomain(domain)
		ClearOutDesiredLRPsInDomain(domain)
	}
})

var _ = AfterSuite(func() {
	for _, domain := range []string{domain, otherDomain} {
		bbsClient.UpsertDomain(domain, 5*time.Minute) //leave the domain around forever so that Diego cleans up if need be
	}

	for _, domain := range []string{domain, otherDomain} {
		ClearOutDesiredLRPsInDomain(domain)
		ClearOutTasksInDomain(domain)
	}
})

func initializeBBSClient() bbs.Client {
	bbsURL, err := url.Parse(bbsAddress)
	Ω(err).ShouldNot(HaveOccurred())

	if bbsURL.Scheme != "https" {
		return bbs.NewClient(bbsAddress)
	}

	bbsClient, err := bbs.NewSecureSkipVerifyClient(bbsAddress, bbsClientCert, bbsClientKey, 0, 0)
	Ω(err).ShouldNot(HaveOccurred())
	return bbsClient
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"io"
	"net/http"
	"os"
	"path/filepath"

	"github.com/codegangsta/cli"
)

// UpdateCommand updates this binary if there's an update available.
func UpdateCommand(c *cli.Context) int {
	checkUpdate := NewCheckUpdate()

	// by pass random checking to force checking for update
	checkUpdate.ForceCheck = true

	yesUpdate, err := checkUpdate.IsUpdateAvailable()
	if err != nil {
		fmt.Printf("Error checking if update is available: '%s'\n", err)
		return 1
	}

	if !yesUpdate {
		fmt.Println("No update available.")
		return 0
	}

	s, err := newService()
	if err != nil {
		fmt.Printf("Error stopping %s: '%s'\n", KlientName, err)
		return 1
	}

	fmt.Printf("An update is available...\n")
	fmt.Printf("Stopping %s...\n", KlientName)

	// stop klient before we update it
	if err := s.Stop(); err != nil {
		fmt.Printf("Error stopping %s: '%s'\n", KlientName, err)
		return 1
	}

	// download klient and kd to approprite place
	dlPaths := map[string]string{
		// /opt/kite/klient/klient
		filepath.Join(KlientDirectory, "klient"): S3KlientPath,

		// /usr/local/bin/kd
		filepath.Join(KlientctlDirectory, "kd"): S3KlientctlPath,
	}

	fmt.Println("Updating...")

	for localPath, remotePath := range dlPaths {
		if err := downloadRemoteToLocal(remotePath, localPath); err != nil {
			fmt.Printf("Error updating %s: '%s'\n", Name, err)
			return 1
		}
	}

	// start klient now that it's done updating
	if err := s.Start(); err != nil {
		fmt.Printf("Error starting %s: '%s'\n", KlientName, err)
		return 1
	}

	fmt.Printf("Successfully updated to latest version of %s.\n", Name)
	return 0
}

func downloadRemoteToLocal(remotePath, destPath string) error {
	// create the destination dir, if needed.
	if err := os.MkdirAll(filepath.Dir(destPath), 0755); err != nil {
		return err
	}

	// open file in specified path to write to
	perms := os.O_WRONLY | os.O_CREATE | os.O_TRUNC
	binFile, err := os.OpenFile(destPath, perms, 0755)
	if err != nil {
		if binFile != nil {
			binFile.Close()
		}

		return nil
	}

	// get from remote
	res, err := http.Get(remotePath)
	if err != nil {
		return err
	}
	defer res.Body.Close()

	// copy remote file to destination path
	if _, err := io.Copy(binFile, res.Body); err != nil {
		return err
	}

	return binFile.Close()
}
<commit_msg>Revert "logging: Removed logging creation from update"<commit_after>package main

import (
	"fmt"
	"io"
	"net/http"
	"os"
	"path/filepath"

	"github.com/codegangsta/cli"
	"github.com/koding/klientctl/logging"
)

// UpdateCommand updates this binary if there's an update available.
func UpdateCommand(c *cli.Context) int {
	// Create the log file early in the install process, so that we can log the
	// install process and any troubles encountered.
	if err := createLogFile(LogFilePath); err != nil {
		fmt.Println(`Error: Unable to create log files.`)
		return 1
	}

	// Now that we created the logfile, set our logger handler to use that newly created
	// file, so that we can log errors during installation.
	f, err := os.OpenFile(LogFilePath, os.O_WRONLY|os.O_APPEND, 0666)
	if err != nil {
		fmt.Println(`Error: Unable to open log files.`)
		return 1
	}
	log.SetHandler(logging.NewWriterHandler(f))
	log.Infof("Update created log file")

	checkUpdate := NewCheckUpdate()

	// by pass random checking to force checking for update
	checkUpdate.ForceCheck = true

	yesUpdate, err := checkUpdate.IsUpdateAvailable()
	if err != nil {
		fmt.Printf("Error checking if update is available: '%s'\n", err)
		return 1
	}

	if !yesUpdate {
		fmt.Println("No update available.")
		return 0
	}

	s, err := newService()
	if err != nil {
		fmt.Printf("Error stopping %s: '%s'\n", KlientName, err)
		return 1
	}

	fmt.Printf("An update is available...\n")
	fmt.Printf("Stopping %s...\n", KlientName)

	// stop klient before we update it
	if err := s.Stop(); err != nil {
		fmt.Printf("Error stopping %s: '%s'\n", KlientName, err)
		return 1
	}

	// download klient and kd to approprite place
	dlPaths := map[string]string{
		// /opt/kite/klient/klient
		filepath.Join(KlientDirectory, "klient"): S3KlientPath,

		// /usr/local/bin/kd
		filepath.Join(KlientctlDirectory, "kd"): S3KlientctlPath,
	}

	fmt.Println("Updating...")

	for localPath, remotePath := range dlPaths {
		if err := downloadRemoteToLocal(remotePath, localPath); err != nil {
			fmt.Printf("Error updating %s: '%s'\n", Name, err)
			return 1
		}
	}

	// start klient now that it's done updating
	if err := s.Start(); err != nil {
		fmt.Printf("Error starting %s: '%s'\n", KlientName, err)
		return 1
	}

	fmt.Printf("Successfully updated to latest version of %s.\n", Name)
	return 0
}

func downloadRemoteToLocal(remotePath, destPath string) error {
	// create the destination dir, if needed.
	if err := os.MkdirAll(filepath.Dir(destPath), 0755); err != nil {
		return err
	}

	// open file in specified path to write to
	perms := os.O_WRONLY | os.O_CREATE | os.O_TRUNC
	binFile, err := os.OpenFile(destPath, perms, 0755)
	if err != nil {
		if binFile != nil {
			binFile.Close()
		}

		return nil
	}

	// get from remote
	res, err := http.Get(remotePath)
	if err != nil {
		return err
	}
	defer res.Body.Close()

	// copy remote file to destination path
	if _, err := io.Copy(binFile, res.Body); err != nil {
		return err
	}

	return binFile.Close()
}
<|endoftext|>


<commit_before>// Copyright 2012 Aaron Jacobs. All Rights Reserved.
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package http_test

import (
	"github.com/jacobsa/aws/s3/http"
	. "github.com/jacobsa/oglematchers"
	. "github.com/jacobsa/ogletest"
	sys_http "net/http"
	"net/http/httptest"
	"net/url"
	"testing"
)

func TestConn(t *testing.T) { RunTests(t) }

////////////////////////////////////////////////////////////////////////
// Helpers
////////////////////////////////////////////////////////////////////////

type localHandler struct {
	// To be returned.
	statusCode int
	body []byte
}

func (h *localHandler) ServeHTTP(w sys_http.ResponseWriter, r *sys_http.Request) {
	w.WriteHeader(h.statusCode)
	if _, err := w.Write(h.body); err != nil {
		panic(err)
	}
}

type ConnTest struct {
	handler localHandler
	server *httptest.Server
	endpoint *url.URL
}

func init() { RegisterTestSuite(&ConnTest{}) }

func (t *ConnTest) SetUp(i *TestInfo) {
	t.server = httptest.NewServer(&t.handler)

	var err error
	t.endpoint, err = url.Parse(t.server.URL)
	AssertEq(nil, err)
}

func (t *ConnTest) TearDown() {
	t.server.Close()
}

////////////////////////////////////////////////////////////////////////
// Tests
////////////////////////////////////////////////////////////////////////

func (t *ConnTest) InvalidScheme() {
	// Connection
	_, err := http.NewConn(&url.URL{Scheme: "taco", Host: "localhost"})

	ExpectThat(err, Error(HasSubstr("scheme")))
	ExpectThat(err, Error(HasSubstr("taco")))
}

func (t *ConnTest) UnknownHost() {
	// Connection
	conn, err := http.NewConn(&url.URL{Scheme: "http", Host: "foo.sidofhdksjhf"})
	AssertEq(nil, err)

	// Request
	req := &http.Request{
		Verb: "GET",
		Path: "/foo",
		Headers: map[string]string{},
	}

	// Call
	_, err = conn.SendRequest(req)

	ExpectThat(err, Error(HasSubstr("foo.sidofhdksjhf")))
	ExpectThat(err, Error(HasSubstr("no such host")))
}

func (t *ConnTest) InvalidVerb() {
	ExpectEq("TODO", "")
}

func (t *ConnTest) PassesOnRequestInfo() {
	ExpectEq("TODO", "")
}

func (t *ConnTest) ReturnsStatusCode() {
	ExpectEq("TODO", "")
}

func (t *ConnTest) ReturnsBody() {
	// Handler
	t.handler.body = []byte{0xde, 0xad, 0x00, 0xbe, 0xef}

	// Connection
	conn, err := http.NewConn(t.endpoint)
	AssertEq(nil, err)

	// Request
	req := &http.Request{
		Verb: "GET",
		Path: "/",
		Headers: map[string]string{},
	}

	// Call
	resp, err := conn.SendRequest(req)
	AssertEq(nil, err)

	ExpectThat(resp.Body, DeepEquals(t.handler.body))
}

func (t *ConnTest) ServerReturnsEmptyBody() {
	ExpectEq("TODO", "")
}

func (t *ConnTest) HttpsWorksProperly() {
	ExpectEq("TODO", "")
}
<commit_msg>ConnTest.ReturnsStatusCode<commit_after>// Copyright 2012 Aaron Jacobs. All Rights Reserved.
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package http_test

import (
	"github.com/jacobsa/aws/s3/http"
	. "github.com/jacobsa/oglematchers"
	. "github.com/jacobsa/ogletest"
	sys_http "net/http"
	"net/http/httptest"
	"net/url"
	"testing"
)

func TestConn(t *testing.T) { RunTests(t) }

////////////////////////////////////////////////////////////////////////
// Helpers
////////////////////////////////////////////////////////////////////////

type localHandler struct {
	// To be returned.
	statusCode int
	body []byte
}

func (h *localHandler) ServeHTTP(w sys_http.ResponseWriter, r *sys_http.Request) {
	w.WriteHeader(h.statusCode)
	if _, err := w.Write(h.body); err != nil {
		panic(err)
	}
}

type ConnTest struct {
	handler localHandler
	server *httptest.Server
	endpoint *url.URL
}

func init() { RegisterTestSuite(&ConnTest{}) }

func (t *ConnTest) SetUp(i *TestInfo) {
	t.server = httptest.NewServer(&t.handler)

	var err error
	t.endpoint, err = url.Parse(t.server.URL)
	AssertEq(nil, err)
}

func (t *ConnTest) TearDown() {
	t.server.Close()
}

////////////////////////////////////////////////////////////////////////
// Tests
////////////////////////////////////////////////////////////////////////

func (t *ConnTest) InvalidScheme() {
	// Connection
	_, err := http.NewConn(&url.URL{Scheme: "taco", Host: "localhost"})

	ExpectThat(err, Error(HasSubstr("scheme")))
	ExpectThat(err, Error(HasSubstr("taco")))
}

func (t *ConnTest) UnknownHost() {
	// Connection
	conn, err := http.NewConn(&url.URL{Scheme: "http", Host: "foo.sidofhdksjhf"})
	AssertEq(nil, err)

	// Request
	req := &http.Request{
		Verb: "GET",
		Path: "/foo",
		Headers: map[string]string{},
	}

	// Call
	_, err = conn.SendRequest(req)

	ExpectThat(err, Error(HasSubstr("foo.sidofhdksjhf")))
	ExpectThat(err, Error(HasSubstr("no such host")))
}

func (t *ConnTest) InvalidVerb() {
	ExpectEq("TODO", "")
}

func (t *ConnTest) PassesOnRequestInfo() {
	ExpectEq("TODO", "")
}

func (t *ConnTest) ReturnsStatusCode() {
	// Handler
	t.handler.statusCode = 123

	// Connection
	conn, err := http.NewConn(t.endpoint)
	AssertEq(nil, err)

	// Request
	req := &http.Request{
		Verb: "GET",
		Path: "/",
		Headers: map[string]string{},
	}

	// Call
	resp, err := conn.SendRequest(req)
	AssertEq(nil, err)

	ExpectEq(123, resp.StatusCode)
}

func (t *ConnTest) ReturnsBody() {
	// Handler
	t.handler.body = []byte{0xde, 0xad, 0x00, 0xbe, 0xef}

	// Connection
	conn, err := http.NewConn(t.endpoint)
	AssertEq(nil, err)

	// Request
	req := &http.Request{
		Verb: "GET",
		Path: "/",
		Headers: map[string]string{},
	}

	// Call
	resp, err := conn.SendRequest(req)
	AssertEq(nil, err)

	ExpectThat(resp.Body, DeepEquals(t.handler.body))
}

func (t *ConnTest) ServerReturnsEmptyBody() {
	ExpectEq("TODO", "")
}

func (t *ConnTest) HttpsWorksProperly() {
	ExpectEq("TODO", "")
}
<|endoftext|>


<commit_before>package context

import "testing"

func TestUnmarshalNumber(t *testing.T) {

	c := float64(1)
	sv := makevalue(c)
	var i float64
	Unmarshal(sv, &i)
	if c != i {
		t.Errorf("got: %d wanted: %d", i, c)
	}

	d := 1.5
	dv := makevalue(d)
	var ed float64
	Unmarshal(dv, &ed)
	if d != ed {
		t.Errorf("got: %d wanted: %d", ed, d)
	}

	d = 2
	dv = makevalue(d)
	var ei int
	err := Unmarshal(dv, &ei)
	if err == nil {
		t.Error("No error thrown for invalid type")
	}
	if e := "Can not cast int to type reflect.Float64"; e != err.Error() {
		t.Errorf("got:\n%s\nwanted:\n%s\n", e, err.Error())
	}

}

func TestUnmarshalValue(t *testing.T) {
	e := "example"
	input := makevalue(e)
	var s string
	Unmarshal(input, &s)
	if e != s {
		t.Errorf("got: % #v\nwanted: %s", s, e)
	}

	var gsv SassValue
	Unmarshal(input, &gsv)
	if e != gsv {
		t.Errorf("got: % #v\nwanted: %s", gsv, e)
	}

}

func TestUnmarshalComplex(t *testing.T) {
	// Only SassValue supported for lists, is this ok?
	e := []SassValue{"ex1", "ex2"}
	list := makevalue(e)
	var s []SassValue
	Unmarshal(list, &s)

	if len(s) != len(e) {
		t.Error("Length mismatch")
		return
	}

	for i := range e {
		if e[i] != s[i] {
			t.Errorf("got: %v wanted %v", s, e)
		}
	}
}
<commit_msg>float is %f<commit_after>package context

import "testing"

func TestUnmarshalNumber(t *testing.T) {

	c := float64(1)
	sv := makevalue(c)
	var i float64
	Unmarshal(sv, &i)
	if c != i {
		t.Errorf("got: %f wanted: %f", i, c)
	}

	d := 1.5
	dv := makevalue(d)
	var ed float64
	Unmarshal(dv, &ed)
	if d != ed {
		t.Errorf("got: %f wanted: %f", ed, d)
	}

	d = 2
	dv = makevalue(d)
	var ei int
	err := Unmarshal(dv, &ei)
	if err == nil {
		t.Error("No error thrown for invalid type")
	}
	if e := "Can not cast int to type reflect.Float64"; e != err.Error() {
		t.Errorf("got:\n%s\nwanted:\n%s\n", e, err.Error())
	}

}

func TestUnmarshalValue(t *testing.T) {
	e := "example"
	input := makevalue(e)
	var s string
	Unmarshal(input, &s)
	if e != s {
		t.Errorf("got: % #v\nwanted: %s", s, e)
	}

	var gsv SassValue
	Unmarshal(input, &gsv)
	if e != gsv {
		t.Errorf("got: % #v\nwanted: %s", gsv, e)
	}

}

func TestUnmarshalComplex(t *testing.T) {
	// Only SassValue supported for lists, is this ok?
	e := []SassValue{"ex1", "ex2"}
	list := makevalue(e)
	var s []SassValue
	Unmarshal(list, &s)

	if len(s) != len(e) {
		t.Error("Length mismatch")
		return
	}

	for i := range e {
		if e[i] != s[i] {
			t.Errorf("got: %v wanted %v", s, e)
		}
	}
}
<|endoftext|>


<commit_before>package gofpdi

import (
	realgofpdi "github.com/phpdave11/gofpdi"
	"io"
)

// Create new gofpdi instance
var fpdi = realgofpdi.NewImporter()

// gofpdiPdf is a partial interface that only implements the functions we need
// from the PDF generator to put the imported PDF templates on the PDF.
type gofpdiPdf interface {
	ImportObjects(objs map[string][]byte)
	ImportObjPos(objs map[string]map[int]string)
	ImportTemplates(tpls map[string]string)
	UseImportedTemplate(tplName string, x float64, y float64, w float64, h float64)
	SetError(err error)
}

// ImportPage imports a page of a PDF file with the specified box (/MediaBox,
// /TrimBox, /ArtBox, /CropBox, or /BleedBox). Returns a template id that can
// be used with UseImportedTemplate to draw the template onto the page.
func ImportPage(f gofpdiPdf, sourceFile string, pageno int, box string) int {
	// Set source file for fpdi
	fpdi.SetSourceFile(sourceFile)
	// return template id
	return getTemplateID(f, pageno, box)
}

// ImportPage imports a page of a PDF with the specified box (/MediaBox,
// /TrimBox, /ArtBox, /CropBox, or /BleedBox). Returns a template id that can
// be used with UseImportedTemplate to draw the template onto the page.
func ImportPageFromStream(f gofpdiPdf, rs *io.ReadSeeker, pageno int, box string) int {
	// Set source stream for fpdi
	fpdi.SetSourceStream(rs)
	// return template id
	return getTemplateID(f, pageno, box)
}

func getTemplateID(f gofpdiPdf, pageno int, box string) int {
	// Import page
	tpl := fpdi.ImportPage(pageno, box)

	// Import objects into current pdf document
	// Unordered means that the objects will be returned with a sha1 hash instead of an integer
	// The objects themselves may have references to other hashes which will be replaced in ImportObjects()
	tplObjIDs := fpdi.PutFormXobjectsUnordered()

	// Set template names and ids (hashes) in gofpdf
	f.ImportTemplates(tplObjIDs)

	// Get a map[string]string of the imported objects.
	// The map keys will be the ID of each object.
	imported := fpdi.GetImportedObjectsUnordered()

	// Import gofpdi objects into gofpdf
	f.ImportObjects(imported)

	// Get a map[string]map[int]string of the object hashes and their positions within each object,
	// to be replaced with object ids (integers).
	importedObjPos := fpdi.GetImportedObjHashPos()

	// Import gofpdi object hashes and their positions into gopdf
	f.ImportObjPos(importedObjPos)

	return tpl
}

// UseImportedTemplate draws the template onto the page at x,y. If w is 0, the
// template will be scaled to fit based on h. If h is 0, the template will be
// scaled to fit based on w.
func UseImportedTemplate(f gofpdiPdf, tplid int, x float64, y float64, w float64, h float64) {
	// Get values from fpdi
	tplName, scaleX, scaleY, tX, tY := fpdi.UseTemplate(tplid, x, y, w, h)

	f.UseImportedTemplate(tplName, scaleX, scaleY, tX, tY)
}

// GetPageSizes returns page dimensions for all pages of the imported pdf.
// Result consists of map[<page number>]map[<box>]map[<dimension>]<value>.
// <page number>: page number, note that page numbers start at 1
// <box>: box identifier, e.g. "/MediaBox"
// <dimension>: dimension string, either "w" or "h"
func GetPageSizes() map[int]map[string]map[string]float64 {
	return fpdi.GetPageSizes()
}
<commit_msg>Corrected comment to match function name<commit_after>package gofpdi

import (
	realgofpdi "github.com/phpdave11/gofpdi"
	"io"
)

// Create new gofpdi instance
var fpdi = realgofpdi.NewImporter()

// gofpdiPdf is a partial interface that only implements the functions we need
// from the PDF generator to put the imported PDF templates on the PDF.
type gofpdiPdf interface {
	ImportObjects(objs map[string][]byte)
	ImportObjPos(objs map[string]map[int]string)
	ImportTemplates(tpls map[string]string)
	UseImportedTemplate(tplName string, x float64, y float64, w float64, h float64)
	SetError(err error)
}

// ImportPage imports a page of a PDF file with the specified box (/MediaBox,
// /TrimBox, /ArtBox, /CropBox, or /BleedBox). Returns a template id that can
// be used with UseImportedTemplate to draw the template onto the page.
func ImportPage(f gofpdiPdf, sourceFile string, pageno int, box string) int {
	// Set source file for fpdi
	fpdi.SetSourceFile(sourceFile)
	// return template id
	return getTemplateID(f, pageno, box)
}

// ImportPageFromStream imports a page of a PDF with the specified box
// (/MediaBox, TrimBox, /ArtBox, /CropBox, or /BleedBox). Returns a template id
// that can be used with UseImportedTemplate to draw the template onto the
// page.
func ImportPageFromStream(f gofpdiPdf, rs *io.ReadSeeker, pageno int, box string) int {
	// Set source stream for fpdi
	fpdi.SetSourceStream(rs)
	// return template id
	return getTemplateID(f, pageno, box)
}

func getTemplateID(f gofpdiPdf, pageno int, box string) int {
	// Import page
	tpl := fpdi.ImportPage(pageno, box)

	// Import objects into current pdf document
	// Unordered means that the objects will be returned with a sha1 hash instead of an integer
	// The objects themselves may have references to other hashes which will be replaced in ImportObjects()
	tplObjIDs := fpdi.PutFormXobjectsUnordered()

	// Set template names and ids (hashes) in gofpdf
	f.ImportTemplates(tplObjIDs)

	// Get a map[string]string of the imported objects.
	// The map keys will be the ID of each object.
	imported := fpdi.GetImportedObjectsUnordered()

	// Import gofpdi objects into gofpdf
	f.ImportObjects(imported)

	// Get a map[string]map[int]string of the object hashes and their positions within each object,
	// to be replaced with object ids (integers).
	importedObjPos := fpdi.GetImportedObjHashPos()

	// Import gofpdi object hashes and their positions into gopdf
	f.ImportObjPos(importedObjPos)

	return tpl
}

// UseImportedTemplate draws the template onto the page at x,y. If w is 0, the
// template will be scaled to fit based on h. If h is 0, the template will be
// scaled to fit based on w.
func UseImportedTemplate(f gofpdiPdf, tplid int, x float64, y float64, w float64, h float64) {
	// Get values from fpdi
	tplName, scaleX, scaleY, tX, tY := fpdi.UseTemplate(tplid, x, y, w, h)

	f.UseImportedTemplate(tplName, scaleX, scaleY, tX, tY)
}

// GetPageSizes returns page dimensions for all pages of the imported pdf.
// Result consists of map[<page number>]map[<box>]map[<dimension>]<value>.
// <page number>: page number, note that page numbers start at 1
// <box>: box identifier, e.g. "/MediaBox"
// <dimension>: dimension string, either "w" or "h"
func GetPageSizes() map[int]map[string]map[string]float64 {
	return fpdi.GetPageSizes()
}
<|endoftext|>