<commit_before>package main

import (
	"bufio"
	"errors"
	"flag"
	"fmt"
	"log"
	"os"
	"regexp"
	"strconv"
	"strings"
)

func readLine(scanner *bufio.Scanner, replace_lines IntSet) {

	scanner.Split(bufio.ScanLines)

	line := 1

	ra, _ := regexp.Compile("[^\\s]")

	for scanner.Scan() {
		_, s := replace_lines[line]
		if s {
			fmt.Printf("%d: %v\n", line, ra.ReplaceAllString(scanner.Text(), "-"))
		} else {
			fmt.Printf("%d: %v\n", line, scanner.Text())
		}
		line += 1
	}

	if err := scanner.Err(); err != nil {
		log.Fatal(err)
	}

}

func Exists(name string) bool {
	if _, err := os.Stat(name); err != nil {
		if os.IsNotExist(err) {
			return false
		}
	}
	return true
}

// set of ints
type IntSet map[int]struct{}

// set of strings
type StrSlice []string

func (i *IntSet) String() string {
	return fmt.Sprint(*i)
}

func (i *IntSet) Set(value string) error {
	if len(*i) > 0 {
		return errors.New("line flag already set")
	}
	for _, n := range strings.Split(value, ",") {
		num, err := strconv.Atoi(n)
		if err != nil {
			continue
		}
		if _, found := (*i)[num]; found {
			continue
		}
		(*i)[num] = struct{}{}
	}
	return nil
}

func (s *StrSlice) String() string {
	return fmt.Sprint(*s)
}

func (s *StrSlice) Set(value string) error {
	*s = append(*s, value)
	return nil
}

func main() {

	var replace_lines = IntSet{}
	var replace_strings StrSlice

	flag.Var(&replace_lines, "l", "Number of the line(s) to be replaced")
	flag.Var(&replace_strings, "r", "Word to be replaced")

	flag.Parse()

	fmt.Println("--:", flag.NArg(), flag.Args(), replace_lines, replace_strings)

	stat, _ := os.Stdin.Stat()
	if (stat.Mode() & os.ModeCharDevice) == 0 {
		readLine(bufio.NewScanner(os.Stdin), replace_lines)
	} else {
		if flag.NArg() != 1 {
			fmt.Println("No filename specified")
			os.Exit(1)
		}
		f := flag.Arg(0)
		if Exists(f) {
			file, err := os.Open(f)
			defer file.Close()
			if err != nil {
				log.Fatal(err)
			}
			readLine(bufio.NewScanner(file), replace_lines)
		}
	}
}
<commit_msg>	modified:   gist.go<commit_after>package main

import (
	"bufio"
	"errors"
	"flag"
	"fmt"
	"log"
	"os"
	"regexp"
	"strconv"
	"strings"
)

func readLine(scanner *bufio.Scanner, replace_lines IntSet) {

	scanner.Split(bufio.ScanLines)

	line := 1

	ra, _ := regexp.Compile("[^\\s]")

	for scanner.Scan() {
		_, s := replace_lines[line]
		if s {
			fmt.Printf("%d: %v\n", line, ra.ReplaceAllString(scanner.Text(), "-"))
		} else {
			fmt.Printf("%d: %v\n", line, scanner.Text())
		}
		line += 1
	}

	if err := scanner.Err(); err != nil {
		log.Fatal(err)
	}

}

func Exists(name string) bool {
	if _, err := os.Stat(name); err != nil {
		if os.IsNotExist(err) {
			return false
		}
	}
	return true
}

// set of ints
type IntSet map[int]struct{}

// set of strings
type StrSlice []string

func (i *IntSet) String() string {
	return fmt.Sprint(*i)
}

func (i *IntSet) Set(value string) error {
	if len(*i) > 0 {
		return errors.New("line flag already set")
	}
	for _, n := range strings.Split(value, ",") {
		num, err := strconv.Atoi(n)
		if err != nil {
			continue
		}
		if _, found := (*i)[num]; found {
			continue
		}
		(*i)[num] = struct{}{}
	}
	return nil
}

func (s *StrSlice) String() string {
	return fmt.Sprint(*s)
}

func (s *StrSlice) Set(value string) error {
	*s = append(*s, value)
	return nil
}

func main() {

	var replace_lines = IntSet{}
	var replace_strings StrSlice

	flag.Var(&replace_lines, "l", "Number of the line(s) to be replaced")
	flag.Var(&replace_strings, "r", "Word to be replaced")

	flag.Parse()

	fmt.Println("--:", flag.NArg(), flag.Args(), replace_lines, replace_strings)

	stat, _ := os.Stdin.Stat()
	if (stat.Mode() & os.ModeCharDevice) == 0 {
		readLine(bufio.NewScanner(os.Stdin), replace_lines)
	} else {
		if flag.NArg() != 1 {
			fmt.Println("No filename specified, -h for more info")
			os.Exit(1)
		}
		f := flag.Arg(0)
		if Exists(f) {
			file, err := os.Open(f)
			defer file.Close()
			if err != nil {
				log.Fatal(err)
			}
			readLine(bufio.NewScanner(file), replace_lines)
		}
	}
}
<|endoftext|>


<commit_before>package main

import (
	"bufio"
	"errors"
	"flag"
	"fmt"
	"log"
	"os"
	"regexp"
	"strconv"
	"strings"
)

var (
	SPACES      = regexp.MustCompile("\\s+")
	INVALID_POS = errors.New("invalid position")
)

type Pos struct {
	Start, End *int
}

func (p Pos) String() (result string) {
	if p.Start != nil {
		result = strconv.Itoa(*p.Start)
	}

	result += ":"

	if p.End != nil {
		result += strconv.Itoa(*p.End)
	}

	return
}

func (p *Pos) Set(s string) error {
	p.Start = nil
	p.End = nil

	parts := strings.Split(s, ":")
	if len(parts) < 1 || len(parts) > 2 {
		return INVALID_POS
	}

	if len(parts[0]) > 0 {
		v, err := strconv.Atoi(parts[0])
		if err != nil {
			return err
		}

		p.Start = &v
	}

	if len(parts) == 1 {
		// not a slice
		if p.Start != nil {
			v := *p.Start + 1
			p.End = &v
		}
	} else if len(parts[1]) > 0 {
		v, err := strconv.Atoi(parts[1])
		if err != nil {
			return err
		}

		p.End = &v
	}

	return nil
}

func Slice(source []string, p Pos) []string {
	var start, end int

	if p.Start == nil {
		start = 0
	} else if *p.Start >= len(source) {
		return source[0:0]
	} else if *p.Start < 0 {
		start = len(source) + *p.Start

		if start < 0 {
			start = 0
		}
	} else {
		start = *p.Start
	}

	if p.End == nil || *p.End >= len(source) {
		return source[start:]
	} else if *p.End < 0 {
		end = len(source) + *p.End

		if end < 0 {
			end = 0
		}
	} else {
		end = *p.End
	}

	if end < start {
		end = start
	}

	return source[start:end]
}

func Quote(a []string) []string {
	q := make([]string, len(a))
	for i, s := range a {
		q[i] = fmt.Sprintf("%q", s)
	}

	return q
}

func main() {
	ifs := flag.String("ifs", " ", "input field separator")
	ofs := flag.String("ofs", " ", "input field separator")
	quote := flag.Bool("quote", false, "quote returned fields")
	flag.Parse()

	pos := make([]Pos, len(flag.Args()))

	for i, arg := range flag.Args() {
		pos[i].Set(arg)
	}

	scanner := bufio.NewScanner(os.Stdin)

	for scanner.Scan() {
		if scanner.Err() != nil {
			log.Fatal(scanner.Err())
		}

		line := scanner.Text()

		var fields, result []string

		// split the line according to input field separator
		if *ifs == " " {
			fields = SPACES.Split(strings.TrimSpace(line), -1)
		} else {
			fields = strings.Split(line, *ifs)
		}

		// do some processing
		if len(pos) > 0 {
			result = make([]string, 0)

			for _, p := range pos {
				val := strings.Join(Slice(fields, p), *ifs)
				result = append(result, val)
			}
		} else {
			result = fields
		}

		if *quote {
			result = Quote(result)
		}

		// join the result according to output field separator
		fmt.Println(strings.Join(result, *ofs))
	}
}
<commit_msg>Fixed negative ending (reworked case where there is only a start value)<commit_after>package main

import (
	"bufio"
	"errors"
	"flag"
	"fmt"
	"log"
	"os"
	"regexp"
	"strconv"
	"strings"
)

var (
	SPACES      = regexp.MustCompile("\\s+")
	INVALID_POS = errors.New("invalid position")
)

type Pos struct {
	Start, End *int
}

func (p Pos) String() (result string) {
	if p.Start != nil {
		result = strconv.Itoa(*p.Start)
	}

	result += ":"

	if p.End != nil {
		result += strconv.Itoa(*p.End)
	}

	return
}

func (p *Pos) Set(s string) error {
	p.Start = nil
	p.End = nil

	parts := strings.Split(s, ":")
	if len(parts) < 1 || len(parts) > 2 {
		return INVALID_POS
	}

	if len(parts[0]) > 0 {
		v, err := strconv.Atoi(parts[0])
		if err != nil {
			return err
		}

		p.Start = &v
	}

	if len(parts) == 1 {
		// not a slice
		// note: same pointer (to distinguish from *p.End == *p.Start that returns an empty slice)
		p.End = p.Start
	} else if len(parts[1]) > 0 {
		v, err := strconv.Atoi(parts[1])
		if err != nil {
			return err
		}

		p.End = &v
	}

	return nil
}

func Slice(source []string, p Pos) []string {
	var start, end int

	if p.Start == nil {
		start = 0
	} else if *p.Start >= len(source) {
		return source[0:0]
	} else if *p.Start < 0 {
		start = len(source) + *p.Start

		if start < 0 {
			start = 0
		}
	} else {
		start = *p.Start
	}

	if p.End == p.Start {
		// this should return source[start]
		end = start + 1
	} else if p.End == nil || *p.End >= len(source) {
		return source[start:]
	} else if *p.End < 0 {
		end = len(source) + *p.End
	} else {
		end = *p.End
	}

	if end < start {
		end = start
	}

	return source[start:end]
}

func Quote(a []string) []string {
	q := make([]string, len(a))
	for i, s := range a {
		q[i] = fmt.Sprintf("%q", s)
	}

	return q
}

func main() {
	ifs := flag.String("ifs", " ", "input field separator")
	ofs := flag.String("ofs", " ", "input field separator")
	quote := flag.Bool("quote", false, "quote returned fields")
	flag.Parse()

	pos := make([]Pos, len(flag.Args()))

	for i, arg := range flag.Args() {
		pos[i].Set(arg)
	}

	scanner := bufio.NewScanner(os.Stdin)

	for scanner.Scan() {
		if scanner.Err() != nil {
			log.Fatal(scanner.Err())
		}

		line := scanner.Text()

		var fields, result []string

		// split the line according to input field separator
		if *ifs == " " {
			fields = SPACES.Split(strings.TrimSpace(line), -1)
		} else {
			fields = strings.Split(line, *ifs)
		}

		// do some processing
		if len(pos) > 0 {
			result = make([]string, 0)

			for _, p := range pos {
				val := strings.Join(Slice(fields, p), *ifs)
				result = append(result, val)
			}
		} else {
			result = fields
		}

		if *quote {
			result = Quote(result)
		}

		// join the result according to output field separator
		fmt.Println(strings.Join(result, *ofs))
	}
}
<|endoftext|>


<commit_before>package main

import (
	"bufio"
	"errors"
	"flag"
	"fmt"
	"log"
	"os"
	"path"
	"regexp"
	"strconv"
	"strings"
)

var (
	VERSION     = "0.10.0"
	SPACES      = regexp.MustCompile("\\s+")
	INVALID_POS = errors.New("invalid position")

	OK              = 0
	MATCH_FOUND     = 100
	MATCH_NOT_FOUND = 101
)

type Pos struct {
	Start, End *int
}

func (p Pos) String() (result string) {
	if p.Start != nil {
		result = strconv.Itoa(*p.Start)
	}

	result += ":"

	if p.End != nil {
		result += strconv.Itoa(*p.End)
	}

	return
}

func (p *Pos) Set(s string) error {
	p.Start = nil
	p.End = nil

	parts := strings.Split(s, ":")
	if len(parts) < 1 || len(parts) > 2 {
		return INVALID_POS
	}

	if len(parts[0]) > 0 {
		v, err := strconv.Atoi(parts[0])
		if err != nil {
			return err
		}

		p.Start = &v
	}

	if len(parts) == 1 {
		// not a slice
		// note: same pointer (to distinguish from *p.End == *p.Start that returns an empty slice)
		p.End = p.Start
	} else if len(parts[1]) > 0 {
		v, err := strconv.Atoi(parts[1])
		if err != nil {
			return err
		}

		p.End = &v
	}

	return nil
}

func Slice(source []string, p Pos) []string {
	var start, end int

	if p.Start == nil {
		start = 0
	} else if *p.Start >= len(source) {
		return source[0:0]
	} else if *p.Start < 0 {
		start = len(source) + *p.Start

		if start < 0 {
			start = 0
		}
	} else {
		start = *p.Start
	}

	if p.End == p.Start {
		// this should return source[start]
		end = start + 1
	} else if p.End == nil || *p.End >= len(source) {
		return source[start:]
	} else if *p.End < 0 {
		end = len(source) + *p.End
	} else {
		end = *p.End
	}

	if end < start {
		end = start
	}

	return source[start:end]
}

func Quote(a []string) []string {
	q := make([]string, len(a))
	for i, s := range a {
		q[i] = fmt.Sprintf("%q", s)
	}

	return q
}

func Unquote(a []string) []string {
	q := make([]string, len(a))
	for i, s := range a {
		q[i] = strings.Trim(s, `"'`)
	}

	return q
}

func Print(format string, a []string) {
	printable := make([]interface{}, len(a))

	for i, v := range a {
		printable[i] = v
	}

	fmt.Printf(format, printable...)
}

func main() {
	version := flag.Bool("version", false, "print version and exit")
	quote := flag.Bool("quote", false, "quote returned fields")
	unquote := flag.Bool("unquote", false, "quote returned fields")
	ifs := flag.String("ifs", " ", "input field separator")
	ire := flag.String("ifs-re", "", "input field separator (as regular expression)")
	ofs := flag.String("ofs", " ", "input field separator")
	re := flag.String("re", "", "regular expression for parsing input")
	grep := flag.String("grep", "", "output only lines that match the regular expression")
	format := flag.String("printf", "", "output is formatted according to specified format")
	matches := flag.String("matches", "", "return status code 100 if any line matches the specified pattern, 101 otherwise")
	after := flag.String("after", "", "process line after specified tag")
	printline := flag.Bool("line", false, "print line numbers")

	flag.Parse()

	if *version {
		fmt.Printf("%s version %s\n", path.Base(os.Args[0]), VERSION)
		return
	}

	pos := make([]Pos, len(flag.Args()))

	for i, arg := range flag.Args() {
		pos[i].Set(arg)
	}

	if len(*format) > 0 && !strings.HasSuffix(*format, "\n") {
		*format += "\n"
	}

	var split_re *regexp.Regexp
	var split_pattern *regexp.Regexp
	var match_pattern *regexp.Regexp
	var grep_pattern *regexp.Regexp
	status_code := OK

	if len(*matches) > 0 {
		match_pattern = regexp.MustCompile(*matches)
		status_code = MATCH_NOT_FOUND
	}

	if len(*grep) > 0 {
		grep_pattern = regexp.MustCompile(*grep)
	}

	if len(*re) > 0 {
		split_pattern = regexp.MustCompile(*re)
	}

	if len(*ire) > 0 {
		split_re = regexp.MustCompile(*ire)
	}

	scanner := bufio.NewScanner(os.Stdin)
	len_after := len(*after)
	lineno := 0

	for scanner.Scan() {
		if scanner.Err() != nil {
			log.Fatal(scanner.Err())
		}

		line := scanner.Text()
		lineno += 1

		if len_after > 0 {
			i := strings.Index(line, *after)
			if i < 0 {
				continue // no match
			}

			line = line[i+len_after:]
		}

		fields := []string{line} // $0 is the full line

		if grep_pattern != nil {
			if matches := grep_pattern.FindStringSubmatch(line); matches != nil {
				fields = matches
			} else {
				continue
			}
		} else if split_pattern != nil {
			if matches := split_pattern.FindStringSubmatch(line); matches != nil {
				fields = matches
			}
		} else if split_re != nil {
			// split line according to input regular expression
			fields = append(fields, split_re.Split(line, -1)...)
		} else if *ifs == " " {
			// split line on spaces (compact multiple spaces)
			fields = append(fields, SPACES.Split(strings.TrimSpace(line), -1)...)
		} else {
			// split line according to input field separator
			fields = append(fields, strings.Split(line, *ifs)...)
		}

		var result []string

		// do some processing
		if len(pos) > 0 {
			result = make([]string, 0)

			for _, p := range pos {
				val := strings.Join(Slice(fields, p), *ifs)
				result = append(result, val)
			}
		} else {
			result = fields[0:1]
		}

		if *unquote {
			result = Unquote(result)
		}

		if *quote {
			result = Quote(result)
		}

		if *printline {
			fmt.Printf("%d: ", lineno)
		}

		if len(*format) > 0 {
			Print(*format, result)
		} else {
			// join the result according to output field separator
			fmt.Println(strings.Join(result, *ofs))
		}

		if match_pattern != nil && match_pattern.MatchString(line) {
			status_code = MATCH_FOUND
		}
	}

	os.Exit(status_code)
}
<commit_msg>added --debug flag and fixed a couple of issues with output field separator<commit_after>package main

import (
	"bufio"
	"errors"
	"flag"
	"fmt"
	"log"
	"os"
	"path"
	"regexp"
	"strconv"
	"strings"
)

var (
	VERSION     = "0.10.0"
	SPACES      = regexp.MustCompile("\\s+")
	INVALID_POS = errors.New("invalid position")

	OK              = 0
	MATCH_FOUND     = 100
	MATCH_NOT_FOUND = 101
)

type Pos struct {
	Start, End *int
}

func (p Pos) String() (result string) {
	if p.Start != nil {
		result = strconv.Itoa(*p.Start)
	} else {
		result += "FIRST"
	}

	result += " TO "

	if p.End != nil {
		result += strconv.Itoa(*p.End)
	} else {
		result += "LAST"
	}

	return
}

func (p *Pos) Set(s string) error {
	p.Start = nil
	p.End = nil

	parts := strings.Split(s, ":")
	if len(parts) < 1 || len(parts) > 2 {
		return INVALID_POS
	}

	if len(parts[0]) > 0 {
		v, err := strconv.Atoi(parts[0])
		if err != nil {
			return err
		}

		p.Start = &v
	}

	if len(parts) == 1 {
		// not a slice
		// note: same pointer (to distinguish from *p.End == *p.Start that returns an empty slice)
		p.End = p.Start
	} else if len(parts[1]) > 0 {
		v, err := strconv.Atoi(parts[1])
		if err != nil {
			return err
		}

		p.End = &v
	}

	return nil
}

func Slice(source []string, p Pos) []string {
	var start, end int

	if p.Start == nil {
		start = 0
	} else if *p.Start >= len(source) {
		return source[0:0]
	} else if *p.Start < 0 {
		start = len(source) + *p.Start

		if start < 0 {
			start = 0
		}
	} else {
		start = *p.Start
	}

	if p.End == p.Start {
		// this should return source[start]
		end = start + 1
	} else if p.End == nil || *p.End >= len(source) {
		return source[start:]
	} else if *p.End < 0 {
		end = len(source) + *p.End
	} else {
		end = *p.End
	}

	if end < start {
		end = start
	}

	return source[start:end]
}

func Quote(a []string) []string {
	q := make([]string, len(a))
	for i, s := range a {
		q[i] = fmt.Sprintf("%q", s)
	}

	return q
}

func Unquote(a []string) []string {
	q := make([]string, len(a))
	for i, s := range a {
		q[i] = strings.Trim(s, `"'`)
	}

	return q
}

func Print(format string, a []string) {
	printable := make([]interface{}, len(a))

	for i, v := range a {
		printable[i] = v
	}

	fmt.Printf(format, printable...)
}

func main() {
	version := flag.Bool("version", false, "print version and exit")
	quote := flag.Bool("quote", false, "quote returned fields")
	unquote := flag.Bool("unquote", false, "quote returned fields")
	ifs := flag.String("ifs", " ", "input field separator")
	ire := flag.String("ifs-re", "", "input field separator (as regular expression)")
	ofs := flag.String("ofs", " ", "output field separator")
	re := flag.String("re", "", "regular expression for parsing input")
	grep := flag.String("grep", "", "output only lines that match the regular expression")
	format := flag.String("printf", "", "output is formatted according to specified format")
	matches := flag.String("matches", "", "return status code 100 if any line matches the specified pattern, 101 otherwise")
	after := flag.String("after", "", "process line after specified tag")
	printline := flag.Bool("line", false, "print line numbers")
	debug := flag.Bool("debug", false, "print debug info")

	flag.Parse()

	if *version {
		fmt.Printf("%s version %s\n", path.Base(os.Args[0]), VERSION)
		return
	}

	pos := make([]Pos, len(flag.Args()))

	for i, arg := range flag.Args() {
		pos[i].Set(arg)
	}

	if len(*format) > 0 && !strings.HasSuffix(*format, "\n") {
		*format += "\n"
	}

	var split_re *regexp.Regexp
	var split_pattern *regexp.Regexp
	var match_pattern *regexp.Regexp
	var grep_pattern *regexp.Regexp
	status_code := OK

	if len(*matches) > 0 {
		match_pattern = regexp.MustCompile(*matches)
		status_code = MATCH_NOT_FOUND
	}

	if len(*grep) > 0 {
		grep_pattern = regexp.MustCompile(*grep)
	}

	if len(*re) > 0 {
		split_pattern = regexp.MustCompile(*re)
	}

	if len(*ire) > 0 {
		split_re = regexp.MustCompile(*ire)
	}

	scanner := bufio.NewScanner(os.Stdin)
	len_after := len(*after)
	lineno := 0

	for scanner.Scan() {
		if scanner.Err() != nil {
			log.Fatal(scanner.Err())
		}

		line := scanner.Text()
		lineno += 1

		if len_after > 0 {
			i := strings.Index(line, *after)
			if i < 0 {
				continue // no match
			}

			line = line[i+len_after:]
		}

		fields := []string{line} // $0 is the full line

		if grep_pattern != nil {
			if matches := grep_pattern.FindStringSubmatch(line); matches != nil {
				fields = matches
			} else {
				continue
			}
		} else if split_pattern != nil {
			if matches := split_pattern.FindStringSubmatch(line); matches != nil {
				fields = matches
			}
		} else if split_re != nil {
			// split line according to input regular expression
			fields = append(fields, split_re.Split(line, -1)...)
		} else if *ifs == " " {
			// split line on spaces (compact multiple spaces)
			fields = append(fields, SPACES.Split(strings.TrimSpace(line), -1)...)
		} else {
			// split line according to input field separator
			fields = append(fields, strings.Split(line, *ifs)...)
		}

		if *debug {
			log.Println("input fields:", fields)
			if len(pos) > 0 {
				log.Println("output fields:", pos)
			}
		}

		var result []string

		// do some processing
		if len(pos) > 0 {
			result = make([]string, 0)

			for _, p := range pos {
				val := strings.Join(Slice(fields, p), *ofs)
				result = append(result, val)
			}
		} else {
			result = fields[0:1]
		}

		if *unquote {
			result = Unquote(result)
		}

		if *quote {
			result = Quote(result)
		}

		if *printline {
			fmt.Printf("%d: ", lineno)
		}

		if len(*format) > 0 {
			Print(*format, result)
		} else {
			// join the result according to output field separator
			fmt.Println(strings.Join(result, *ofs))
		}

		if match_pattern != nil && match_pattern.MatchString(line) {
			status_code = MATCH_FOUND
		}
	}

	os.Exit(status_code)
}
<|endoftext|>


<commit_before>// Copyright (c) 2012, Johan P. P. Samyn <johan.samyn@gmail.com> All rights reserved.
// Use of this source code is governed by the Simplified BSD License
// that can be found in the LICENSE.txt file.

// Package gohg is a Go client library for using the Mercurial dvcs
// using it's Command Server for better performance.
//
// For Mercurial see: http://mercurial/selenic.com/wiki.
// For the Hg Command Server see: http://mercurial.selenic.com/wiki/CommandServer.
package gohg

import (
	"encoding/binary"
	"bytes"
	"fmt"
	"io"
	"log"
	"os"
	"os/exec"
	"path/filepath"
)

const t = "hg serve [OPTION]"

var server *exec.Cmd
var repo string

// pout and pin are to be considered from the point of view of the
// Hg Command Server instance.
var pout io.ReadCloser
var pin io.WriteCloser

type hgMsg struct {
	Ch   string
	Ln   uint
	Data string
}

type hgCmd struct {
	Cmd  string
	Ln   uint
	Args string
}

func init() {
	// fmt.Println("Hello from gohg!")
} // init()

func Connect(hg string, repo_arg string, config []string) error {

	// for example:
	// server = exec.Command("M:\\DEV\\hg-stable\\hg",	// the Hg command
	// 		"-R", "C:\\DEV\\go\\src\\golout\\",			// the repo
	// 		"--config", "ui.interactive=True",			// mandatory settings
	// 		"--config", "extensions.color=!",			// more settings (for Windows)
	// 		"serve", "--cmdserver", "pipe")				// start the Command Server

	// Maybe accept a channel as an extra argument for sending the logging to ?
	// And if it's nil, log into a textfile in the folder of this lib.
	// Also do not override that logfile every launch, but insert a timestamp
	// to mark a new run. Maybe even do this in the init() function ?

	if hg == "" {
		// Use the default Mercurial.
		hg = "hg"
	}

	var err error
	var oriRepo string
	sep := string(os.PathSeparator)
	// The Hg Command Server needs a repository.
	repo = repo_arg

	// first make a correct path from repo
	repo, err = filepath.Abs(repo)
	if err != nil {
		log.Fatal("could not find absolute path for: " + repo)
	}
	repo = filepath.Clean(repo)
	oriRepo = repo

	// If we do not find a Hg repo in the current dir, we search for one
	// up the path, in case we're deeper in it's working copy.
	for {
		_, err = os.Stat(repo + sep + ".hg")
		if err == nil {
			break
		}
		var dir, file string
		dir, file = filepath.Split(repo)
		if dir == "" || file == "" {
			repo = ""
			break
		}
		repo = dir
	}
	if err != nil || repo == "" {
		log.Fatal("could not find a Hg repository at: " + oriRepo)
	}

	// if len(config) > 0 {
	// 	var cfg string
	// 	for i := 0; i < range(config) {
	// 		cfg = cfg + "," + config[i]
	// 	}
	// 	cmd = cmd + "," + cfg
	// }

	server = exec.Command(hg)
	server.Args = append(server.Args, "-R", repo)
	server.Args = append(server.Args,
		// These arguments are fixed.
		"--config", "ui.interactive=True",
		"--config", "extensions.color=!",
		"serve", "--cmdserver", "pipe")

	pout, err = server.StdoutPipe()
	if err != nil {
		log.Fatal("could not connect StdoutPipe: ", err)
	}
	pin, err = server.StdinPipe()
	if err != nil {
		log.Fatal("could not connect StdinPipe: ", err)
	}
	if err := server.Start(); err != nil {
		log.Fatal("could not start the Hg Command Server: ", err)
	}
	// temporarily, to avoid compilation error that pin is not used
	_, err = pin.Write(make([]byte, 0))

	s := make([]byte, 1+4+1024)
	_, err = pout.Read(s)
	if err != io.EOF && err != nil {
		log.Fatal(err)
	}
	if len(s) == 0 {
		log.Fatal("no data received from Hg Command Server")
	}
	var ln uint32
	buf := bytes.NewBuffer(s[1:5])
	err = binary.Read(buf, binary.BigEndian, &ln)
	if err != nil {
		fmt.Println("binary.Read failed:", err)
	}
	t := "capabilities:"
	l := len(t)
	if string(s[5:5+l]) != t {
		log.Fatal("could not connect a Hg Command Server")
	}

	fmt.Println("Connected with Hg Command Server at: " + repo)

	return nil

} // Connect()

func Close() error {
	pout.Close()
	pin.Close()
	err := server.Wait()
	if err != nil {
		return err
	}
	fmt.Println("Disconnected from Hg Command Server at: " + repo)
	return nil
} // Close()

func RunCommand() {

} // RunCommand()
<commit_msg>added idea for config settings<commit_after>// Copyright (c) 2012, Johan P. P. Samyn <johan.samyn@gmail.com> All rights reserved.
// Use of this source code is governed by the Simplified BSD License
// that can be found in the LICENSE.txt file.

// Package gohg is a Go client library for using the Mercurial dvcs
// using it's Command Server for better performance.
//
// For Mercurial see: http://mercurial/selenic.com/wiki.
// For the Hg Command Server see: http://mercurial.selenic.com/wiki/CommandServer.
package gohg

import (
	"encoding/binary"
	"bytes"
	"fmt"
	"io"
	"log"
	"os"
	"os/exec"
	"path/filepath"
)

const t = "hg serve [OPTION]"

var server *exec.Cmd
var repo string

// pout and pin are to be considered from the point of view of the
// Hg Command Server instance.
var pout io.ReadCloser
var pin io.WriteCloser

type hgMsg struct {
	Ch   string
	Ln   uint
	Data string
}

type hgCmd struct {
	Cmd  string
	Ln   uint
	Args string
}

func init() {
	// fmt.Println("Hello from gohg!")
} // init()

func Connect(hg string, repo_arg string, config []string) error {

	// for example:
	// server = exec.Command("M:\\DEV\\hg-stable\\hg",	// the Hg command
	// 		"-R", "C:\\DEV\\go\\src\\golout\\",			// the repo
	// 		"--config", "ui.interactive=True",			// mandatory settings
	// 		"--config", "extensions.color=!",			// more settings (for Windows)
	// 		"serve", "--cmdserver", "pipe")				// start the Command Server

	// Maybe accept a channel as an extra argument for sending the logging to ?
	// And if it's nil, log into a textfile in the folder of this lib.
	// Also do not override that logfile every launch, but insert a timestamp
	// to mark a new run. Maybe even do this in the init() function ?

	if hg == "" {
		// Use the default Mercurial.
		hg = "hg"
	}

	var err error
	var oriRepo string
	sep := string(os.PathSeparator)
	// The Hg Command Server needs a repository.
	repo = repo_arg

	// first make a correct path from repo
	repo, err = filepath.Abs(repo)
	if err != nil {
		log.Fatal("could not find absolute path for: " + repo)
	}
	repo = filepath.Clean(repo)
	oriRepo = repo

	// If we do not find a Hg repo in the current dir, we search for one
	// up the path, in case we're deeper in it's working copy.
	for {
		_, err = os.Stat(repo + sep + ".hg")
		if err == nil {
			break
		}
		var dir, file string
		dir, file = filepath.Split(repo)
		if dir == "" || file == "" {
			repo = ""
			break
		}
		repo = dir
	}
	if err != nil || repo == "" {
		log.Fatal("could not find a Hg repository at: " + oriRepo)
	}

	// Maybe we can also offer the possibility of a config file?
	// f.i.: a file gohg.cfg in the same folder as the gohg.exe,
	// and a section per repo, and one "general" section.

	// if len(config) > 0 {
	// 	var cfg string
	// 	for i := 0; i < range(config) {
	// 		cfg = cfg + "," + config[i]
	// 	}
	// 	cmd = cmd + "," + cfg
	// }

	server = exec.Command(hg)
	server.Args = append(server.Args, "-R", repo)
	server.Args = append(server.Args,
		// These arguments are fixed.
		"--config", "ui.interactive=True",
		"--config", "extensions.color=!",
		"serve", "--cmdserver", "pipe")

	pout, err = server.StdoutPipe()
	if err != nil {
		log.Fatal("could not connect StdoutPipe: ", err)
	}
	pin, err = server.StdinPipe()
	if err != nil {
		log.Fatal("could not connect StdinPipe: ", err)
	}
	if err := server.Start(); err != nil {
		log.Fatal("could not start the Hg Command Server: ", err)
	}
	// temporarily, to avoid compilation error that pin is not used
	_, err = pin.Write(make([]byte, 0))

	s := make([]byte, 1+4+1024)
	_, err = pout.Read(s)
	if err != io.EOF && err != nil {
		log.Fatal(err)
	}
	if len(s) == 0 {
		log.Fatal("no data received from Hg Command Server")
	}
	var ln uint32
	buf := bytes.NewBuffer(s[1:5])
	err = binary.Read(buf, binary.BigEndian, &ln)
	if err != nil {
		fmt.Println("binary.Read failed:", err)
	}
	t := "capabilities:"
	l := len(t)
	if string(s[5:5+l]) != t {
		log.Fatal("could not connect a Hg Command Server")
	}

	fmt.Println("Connected with Hg Command Server at: " + repo)

	return nil

} // Connect()

func Close() error {
	pout.Close()
	pin.Close()
	err := server.Wait()
	if err != nil {
		return err
	}
	fmt.Println("Disconnected from Hg Command Server at: " + repo)
	return nil
} // Close()

func RunCommand() {

} // RunCommand()
<|endoftext|>


<commit_before>// Copyright (C) 2016 JT Olds
// See LICENSE for copying information

package whgoth

import (
	"crypto/rand"
	"encoding/hex"
	"log"
	"net/http"
	"net/url"

	"github.com/jtolds/webhelp/whcompat"
	"github.com/jtolds/webhelp/wherr"
	"github.com/jtolds/webhelp/whmux"
	"github.com/jtolds/webhelp/whredir"
	"github.com/jtolds/webhelp/whroute"
	"github.com/jtolds/webhelp/whsess"
	"github.com/markbates/goth"
	"github.com/spacemonkeygo/errors"
	"golang.org/x/net/context"
)

type AuthProvider struct {
	goth.Provider
	baseURL          string
	sessionNamespace string

	whmux.Dir
}

func newAuthProvider(p goth.Provider, baseURL, sessionNamespace string) (
	a *AuthProvider) {
	a = &AuthProvider{
		Provider:         p,
		baseURL:          baseURL,
		sessionNamespace: sessionNamespace,
	}
	a.Dir = whmux.Dir{
		"login":    whmux.Exact(http.HandlerFunc(a.login)),
		"callback": whmux.Exact(http.HandlerFunc(a.callback)),
	}
	return a
}

func (a *AuthProvider) login(w http.ResponseWriter, r *http.Request) {
	ctx := whcompat.Context(r)

	u, err := a.User(ctx)
	if err == nil && u != nil {
		whredir.Redirect(w, r, safeRedirect(r.FormValue("redirect_to"), "/"))
		return
	}

	state := newState()
	sess, err := a.Provider.BeginAuth(ctx, state)
	if err != nil {
		wherr.Handle(w, r, err)
		return
	}

	url, err := sess.GetAuthURL()
	if err != nil {
		wherr.Handle(w, r, err)
		return
	}

	session, err := whsess.Load(ctx, a.sessionNamespace)
	if err != nil {
		wherr.Handle(w, r, err)
		return
	}
	for key := range session.Values {
		delete(session.Values, key)
	}
	session.Values["state"] = state
	session.Values["logged_in"] = false
	session.Values["redirect_to"] = safeRedirect(r.FormValue("redirect_to"), "/")
	session.Values["auth"] = sess.Marshal()
	err = session.Save(w)
	if err != nil {
		wherr.Handle(w, r, err)
		return
	}

	whredir.Redirect(w, r, url)
}

func (a *AuthProvider) Logout(ctx context.Context, w http.ResponseWriter) (
	err error) {
	session, err := whsess.Load(ctx, a.sessionNamespace)
	if err != nil {
		return err
	}
	return session.Clear(w)
}

func (a *AuthProvider) callback(w http.ResponseWriter, r *http.Request) {
	ctx := whcompat.Context(r)
	session, err := whsess.Load(ctx, a.sessionNamespace)
	if err != nil {
		wherr.Handle(w, r, err)
		return
	}

	if loggedIn, _ := session.Values["logged_in"].(bool); loggedIn {
		wherr.Handle(w, r, wherr.BadRequest.New("already logged in"))
		return
	}

	auth, ok := session.Values["auth"].(string)
	if !ok {
		wherr.Handle(w, r, wherr.InternalServerError.New(
			"no existing session found"))
		return
	}

	sess, err := a.Provider.UnmarshalSession(auth)
	if err != nil {
		wherr.Handle(w, r, err)
		return
	}

	authToken, err := sess.Authorize(ctx, a.Provider, r.URL.Query())
	if err != nil {
		wherr.Handle(w, r, err)
		return
	}

	redirectTo, _ := session.Values["redirect_to"].(string)
	session.Values["auth_token"] = authToken
	session.Values["logged_in"] = true
	session.Values["redirect_to"] = nil
	session.Values["auth"] = sess.Marshal()
	err = session.Save(w)
	if err != nil {
		wherr.Handle(w, r, err)
		return
	}

	whredir.Redirect(w, r, safeRedirect(redirectTo, "/"))
}

func (a *AuthProvider) User(ctx context.Context) (*goth.User, error) {
	session, err := whsess.Load(ctx, a.sessionNamespace)
	if err != nil {
		return nil, err
	}

	if loggedIn, _ := session.Values["logged_in"].(bool); !loggedIn {
		return nil, nil
	}

	auth, ok := session.Values["auth"].(string)
	if !ok {
		return nil, nil
	}

	sess, err := a.Provider.UnmarshalSession(auth)
	if err != nil {
		log.Printf("failed to unmarshal session: %v", err)
		return nil, nil
	}

	u, err := a.Provider.FetchUser(ctx, sess)
	if err != nil {
		log.Printf("failed to fetch user: %v", err)
		return nil, nil
	}

	if u.UserID == "" || u.Provider == "" {
		log.Printf("user had no user id or provider set")
		return nil, nil
	}
	return &u, nil
}

func (a *AuthProvider) LoginURL(redirectTo string) string {
	return a.baseURL + "/login?" + url.Values{
		"redirect_to": {redirectTo}}.Encode()
}

type AuthProviders struct {
	baseURL   string
	providers []*AuthProvider

	whmux.Dir
}

func NewAuthProviders(baseURL, sessionNamespace string,
	providers ...goth.Provider) (a *AuthProviders) {
	p := make([]*AuthProvider, 0, len(providers))
	pMux := make(whmux.Dir, len(providers))
	for _, provider := range providers {
		w := newAuthProvider(provider,
			baseURL+"/provider/"+provider.Name(),
			sessionNamespace+"."+provider.Name())
		p = append(p, w)
		pMux[provider.Name()] = w
	}
	a = &AuthProviders{
		baseURL:   baseURL,
		providers: p,
	}
	a.Dir = whmux.Dir{
		"logout":   whmux.Exact(http.HandlerFunc(a.logout)),
		"provider": pMux,
	}
	return a
}

func (a *AuthProviders) Logout(ctx context.Context, w http.ResponseWriter) (
	err error) {
	var errs errors.ErrorGroup
	for _, provider := range a.providers {
		errs.Add(provider.Logout(ctx, w))
	}
	return errs.Finalize()
}

func (a *AuthProviders) logout(w http.ResponseWriter, r *http.Request) {
	err := a.Logout(whcompat.Context(r), w)
	if err != nil {
		wherr.Handle(w, r, err)
		return
	}
	whredir.Redirect(w, r, safeRedirect(r.FormValue("redirect_to"), "/"))
}

func safeRedirect(redirectTo, def string) string {
	u, err := url.Parse(redirectTo)
	if err != nil {
		return def
	}
	if u.Path == "" {
		return def
	}
	return u.Path
}

func (a *AuthProviders) Providers() []*AuthProvider {
	return a.providers
}

func (a *AuthProviders) User(ctx context.Context) (*goth.User, error) {
	for _, provider := range a.providers {
		u, err := provider.User(ctx)
		if err != nil || u != nil {
			return u, err
		}
	}
	return nil, nil
}

func (a *AuthProviders) RequireUser(
	authorizedHandler, unauthorizedHandler http.Handler) http.Handler {
	return whroute.HandlerFunc(authorizedHandler,
		func(w http.ResponseWriter, r *http.Request) {
			u, err := a.User(whcompat.Context(r))
			if err != nil {
				wherr.Handle(w, r, err)
				return
			}
			if u == nil {
				unauthorizedHandler.ServeHTTP(w, r)
			} else {
				authorizedHandler.ServeHTTP(w, r)
			}
		})
}

func (a *AuthProviders) LogoutURL(redirectTo string) string {
	return a.baseURL + "/logout?" + url.Values{
		"redirect_to": {redirectTo}}.Encode()
}

func newState() string {
	var p [16]byte
	_, err := rand.Read(p[:])
	if err != nil {
		panic(err)
	}
	return hex.EncodeToString(p[:])
}
<commit_msg>webhelp moved<commit_after>// Copyright (C) 2016 JT Olds
// See LICENSE for copying information

package whgoth

import (
	"crypto/rand"
	"encoding/hex"
	"log"
	"net/http"
	"net/url"

	"gopkg.in/webhelp.v1/whcompat"
	"gopkg.in/webhelp.v1/wherr"
	"gopkg.in/webhelp.v1/whmux"
	"gopkg.in/webhelp.v1/whredir"
	"gopkg.in/webhelp.v1/whroute"
	"gopkg.in/webhelp.v1/whsess"
	"github.com/markbates/goth"
	"github.com/spacemonkeygo/errors"
	"golang.org/x/net/context"
)

type AuthProvider struct {
	goth.Provider
	baseURL          string
	sessionNamespace string

	whmux.Dir
}

func newAuthProvider(p goth.Provider, baseURL, sessionNamespace string) (
	a *AuthProvider) {
	a = &AuthProvider{
		Provider:         p,
		baseURL:          baseURL,
		sessionNamespace: sessionNamespace,
	}
	a.Dir = whmux.Dir{
		"login":    whmux.Exact(http.HandlerFunc(a.login)),
		"callback": whmux.Exact(http.HandlerFunc(a.callback)),
	}
	return a
}

func (a *AuthProvider) login(w http.ResponseWriter, r *http.Request) {
	ctx := whcompat.Context(r)

	u, err := a.User(ctx)
	if err == nil && u != nil {
		whredir.Redirect(w, r, safeRedirect(r.FormValue("redirect_to"), "/"))
		return
	}

	state := newState()
	sess, err := a.Provider.BeginAuth(ctx, state)
	if err != nil {
		wherr.Handle(w, r, err)
		return
	}

	url, err := sess.GetAuthURL()
	if err != nil {
		wherr.Handle(w, r, err)
		return
	}

	session, err := whsess.Load(ctx, a.sessionNamespace)
	if err != nil {
		wherr.Handle(w, r, err)
		return
	}
	for key := range session.Values {
		delete(session.Values, key)
	}
	session.Values["state"] = state
	session.Values["logged_in"] = false
	session.Values["redirect_to"] = safeRedirect(r.FormValue("redirect_to"), "/")
	session.Values["auth"] = sess.Marshal()
	err = session.Save(w)
	if err != nil {
		wherr.Handle(w, r, err)
		return
	}

	whredir.Redirect(w, r, url)
}

func (a *AuthProvider) Logout(ctx context.Context, w http.ResponseWriter) (
	err error) {
	session, err := whsess.Load(ctx, a.sessionNamespace)
	if err != nil {
		return err
	}
	return session.Clear(w)
}

func (a *AuthProvider) callback(w http.ResponseWriter, r *http.Request) {
	ctx := whcompat.Context(r)
	session, err := whsess.Load(ctx, a.sessionNamespace)
	if err != nil {
		wherr.Handle(w, r, err)
		return
	}

	if loggedIn, _ := session.Values["logged_in"].(bool); loggedIn {
		wherr.Handle(w, r, wherr.BadRequest.New("already logged in"))
		return
	}

	auth, ok := session.Values["auth"].(string)
	if !ok {
		wherr.Handle(w, r, wherr.InternalServerError.New(
			"no existing session found"))
		return
	}

	sess, err := a.Provider.UnmarshalSession(auth)
	if err != nil {
		wherr.Handle(w, r, err)
		return
	}

	authToken, err := sess.Authorize(ctx, a.Provider, r.URL.Query())
	if err != nil {
		wherr.Handle(w, r, err)
		return
	}

	redirectTo, _ := session.Values["redirect_to"].(string)
	session.Values["auth_token"] = authToken
	session.Values["logged_in"] = true
	session.Values["redirect_to"] = nil
	session.Values["auth"] = sess.Marshal()
	err = session.Save(w)
	if err != nil {
		wherr.Handle(w, r, err)
		return
	}

	whredir.Redirect(w, r, safeRedirect(redirectTo, "/"))
}

func (a *AuthProvider) User(ctx context.Context) (*goth.User, error) {
	session, err := whsess.Load(ctx, a.sessionNamespace)
	if err != nil {
		return nil, err
	}

	if loggedIn, _ := session.Values["logged_in"].(bool); !loggedIn {
		return nil, nil
	}

	auth, ok := session.Values["auth"].(string)
	if !ok {
		return nil, nil
	}

	sess, err := a.Provider.UnmarshalSession(auth)
	if err != nil {
		log.Printf("failed to unmarshal session: %v", err)
		return nil, nil
	}

	u, err := a.Provider.FetchUser(ctx, sess)
	if err != nil {
		log.Printf("failed to fetch user: %v", err)
		return nil, nil
	}

	if u.UserID == "" || u.Provider == "" {
		log.Printf("user had no user id or provider set")
		return nil, nil
	}
	return &u, nil
}

func (a *AuthProvider) LoginURL(redirectTo string) string {
	return a.baseURL + "/login?" + url.Values{
		"redirect_to": {redirectTo}}.Encode()
}

type AuthProviders struct {
	baseURL   string
	providers []*AuthProvider

	whmux.Dir
}

func NewAuthProviders(baseURL, sessionNamespace string,
	providers ...goth.Provider) (a *AuthProviders) {
	p := make([]*AuthProvider, 0, len(providers))
	pMux := make(whmux.Dir, len(providers))
	for _, provider := range providers {
		w := newAuthProvider(provider,
			baseURL+"/provider/"+provider.Name(),
			sessionNamespace+"."+provider.Name())
		p = append(p, w)
		pMux[provider.Name()] = w
	}
	a = &AuthProviders{
		baseURL:   baseURL,
		providers: p,
	}
	a.Dir = whmux.Dir{
		"logout":   whmux.Exact(http.HandlerFunc(a.logout)),
		"provider": pMux,
	}
	return a
}

func (a *AuthProviders) Logout(ctx context.Context, w http.ResponseWriter) (
	err error) {
	var errs errors.ErrorGroup
	for _, provider := range a.providers {
		errs.Add(provider.Logout(ctx, w))
	}
	return errs.Finalize()
}

func (a *AuthProviders) logout(w http.ResponseWriter, r *http.Request) {
	err := a.Logout(whcompat.Context(r), w)
	if err != nil {
		wherr.Handle(w, r, err)
		return
	}
	whredir.Redirect(w, r, safeRedirect(r.FormValue("redirect_to"), "/"))
}

func safeRedirect(redirectTo, def string) string {
	u, err := url.Parse(redirectTo)
	if err != nil {
		return def
	}
	if u.Path == "" {
		return def
	}
	return u.Path
}

func (a *AuthProviders) Providers() []*AuthProvider {
	return a.providers
}

func (a *AuthProviders) User(ctx context.Context) (*goth.User, error) {
	for _, provider := range a.providers {
		u, err := provider.User(ctx)
		if err != nil || u != nil {
			return u, err
		}
	}
	return nil, nil
}

func (a *AuthProviders) RequireUser(
	authorizedHandler, unauthorizedHandler http.Handler) http.Handler {
	return whroute.HandlerFunc(authorizedHandler,
		func(w http.ResponseWriter, r *http.Request) {
			u, err := a.User(whcompat.Context(r))
			if err != nil {
				wherr.Handle(w, r, err)
				return
			}
			if u == nil {
				unauthorizedHandler.ServeHTTP(w, r)
			} else {
				authorizedHandler.ServeHTTP(w, r)
			}
		})
}

func (a *AuthProviders) LogoutURL(redirectTo string) string {
	return a.baseURL + "/logout?" + url.Values{
		"redirect_to": {redirectTo}}.Encode()
}

func newState() string {
	var p [16]byte
	_, err := rand.Read(p[:])
	if err != nil {
		panic(err)
	}
	return hex.EncodeToString(p[:])
}
<|endoftext|>


<commit_before>
package gspt

/*

#include "setproctitle.h"

*/
import "C"

import (
  "os"
  "unsafe"
  "strings"
)

const (
  // These values must match the return values for spt_init1() used in C.
  HaveNone        = iota // 0
  HaveNative      = iota // 1
  HaveReplacement = iota // 2
)

var (
  HaveSetProcTitle int
)

func init() {
  HaveSetProcTitle = int(C.spt_init1());

  if HaveSetProcTitle == HaveReplacement {
    newArgs := make([]string, len(os.Args))
    for i, s := range(os.Args) {
      // Use cgo to force go to make copies of the strings.
      cs := C.CString(s)
      newArgs[i] = C.GoString(cs)
      C.free(unsafe.Pointer(cs))
    }
    os.Args = newArgs

    env := os.Environ()
    for _, kv := range(env) {
      skv := strings.SplitN(kv, "=", 2)
      os.Setenv(skv[0], skv[1])
    }

    argc := C.int(len(os.Args))
    arg0 := C.CString(os.Args[0])
    defer C.free(unsafe.Pointer(arg0))

    C.spt_init2(argc, arg0)
  }
}

func SetProcTitle(title string) {
  cs := C.CString(title)
  defer C.free(unsafe.Pointer(cs))

  C.spt_setproctitle(cs)
}

<commit_msg>Use fixed consts<commit_after>package gspt

/*

#include "setproctitle.h"

*/
import "C"

import (
  "os"
  "unsafe"
  "strings"
)

const (
  // These values must match the return values for spt_init1() used in C.
  HaveNone        = 0
  HaveNative      = 1
  HaveReplacement = 2
)

var (
  HaveSetProcTitle int
)

func init() {
  HaveSetProcTitle = int(C.spt_init1());

  if HaveSetProcTitle == HaveReplacement {
    newArgs := make([]string, len(os.Args))
    for i, s := range(os.Args) {
      // Use cgo to force go to make copies of the strings.
      cs := C.CString(s)
      newArgs[i] = C.GoString(cs)
      C.free(unsafe.Pointer(cs))
    }
    os.Args = newArgs

    env := os.Environ()
    for _, kv := range(env) {
      skv := strings.SplitN(kv, "=", 2)
      os.Setenv(skv[0], skv[1])
    }

    argc := C.int(len(os.Args))
    arg0 := C.CString(os.Args[0])
    defer C.free(unsafe.Pointer(arg0))

    C.spt_init2(argc, arg0)
  }
}

func SetProcTitle(title string) {
  cs := C.CString(title)
  defer C.free(unsafe.Pointer(cs))

  C.spt_setproctitle(cs)
}

<|endoftext|>


<commit_before>package hcsshim

import (
	"crypto/sha1"
	"fmt"
)

type GUID [16]byte

func NewGUID(source string) *GUID {
	h := sha1.Sum([]byte(source))
	var g GUID
	copy(g[0:], h[0:16])
	return &g
}

func (g *GUID) ToString() string {
	return fmt.Sprintf("%x%x%x%x-%x%x-%x%x-%x-%x", g[3], g[2], g[1], g[0], g[5], g[4], g[7], g[6], g[8:10], g[10:])
}
<commit_msg>Fix for GUID ToString.<commit_after>package hcsshim

import (
	"crypto/sha1"
	"fmt"
)

type GUID [16]byte

func NewGUID(source string) *GUID {
	h := sha1.Sum([]byte(source))
	var g GUID
	copy(g[0:], h[0:16])
	return &g
}

func (g *GUID) ToString() string {
	return fmt.Sprintf("%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x-%02x", g[3], g[2], g[1], g[0], g[5], g[4], g[7], g[6], g[8:10], g[10:])
}
<|endoftext|>


<commit_before>package main

import (
	"os"
	"strings"
)

func help() {
	var cmd string
	if len(os.Args) > 1 {
		cmd = os.Args[1]
		if len(os.Args) > 2 && cmd == "help" {
			cmd = os.Args[2]
		}
	}
	cli.Commands.loadUsages()
	topic, command := cli.ParseCmd(cmd)
	switch {
	case topic == nil:
		Printf("Usage: heroku COMMAND [--app APP] [command-specific-options]\n\n")
		Printf("Help topics, type \"heroku help TOPIC\" for more details:\n\n")
		for _, topic := range nonHiddenTopics(cli.Topics) {
			Printf("  heroku %-30s# %s\n", topic.Name, topic.Description)
		}
	case command == nil:
		Printf("Usage: heroku %s:COMMAND [--app APP] [command-specific-options]\n\n", topic.Name)
		printTopicCommandsHelp(topic)
	case command.Command == "":
		printCommandHelp(command)
		// This is a root command so show the other commands in the topic
		// if there are any
		if len(topic.Commands()) > 1 {
			printTopicCommandsHelp(topic)
		}
	default:
		printCommandHelp(command)
	}
	os.Exit(2)
}

func printTopicCommandsHelp(topic *Topic) {
	commands := topic.Commands()
	if len(commands) > 0 {
		Printf("\nCommands for %s, type \"heroku help %s:COMMAND\" for more details:\n\n", topic.Name, topic.Name)
		for _, command := range nonHiddenCommands(commands) {
			Printf(" heroku %-30s # %s\n", command.Usage, command.Description)
		}
	}
}

func printCommandHelp(command *Command) {
	Printf("Usage: heroku %s\n\n", command.Usage)
	Println(indent(command.buildFullHelp()))
}

func nonHiddenTopics(from []*Topic) []*Topic {
	to := make([]*Topic, 0, len(from))
	for _, topic := range from {
		if !topic.Hidden {
			to = append(to, topic)
		}
	}
	return to
}

func nonHiddenCommands(from []*Command) []*Command {
	to := make([]*Command, 0, len(from))
	for _, command := range from {
		if !command.Hidden {
			to = append(to, command)
		}
	}
	return to
}

func indent(s string) string {
	return " " + strings.Join(strings.Split(s, "\n"), "\n ")
}
<commit_msg>exit help successfully<commit_after>package main

import (
	"os"
	"strings"
)

func help() {
	var cmd string
	if len(os.Args) > 1 {
		cmd = os.Args[1]
		if len(os.Args) > 2 && cmd == "help" {
			cmd = os.Args[2]
		}
	}
	cli.Commands.loadUsages()
	topic, command := cli.ParseCmd(cmd)
	switch {
	case topic == nil:
		Printf("Usage: heroku COMMAND [--app APP] [command-specific-options]\n\n")
		Printf("Help topics, type \"heroku help TOPIC\" for more details:\n\n")
		for _, topic := range nonHiddenTopics(cli.Topics) {
			Printf("  heroku %-30s# %s\n", topic.Name, topic.Description)
		}
	case command == nil:
		Printf("Usage: heroku %s:COMMAND [--app APP] [command-specific-options]\n\n", topic.Name)
		printTopicCommandsHelp(topic)
	case command.Command == "":
		printCommandHelp(command)
		// This is a root command so show the other commands in the topic
		// if there are any
		if len(topic.Commands()) > 1 {
			printTopicCommandsHelp(topic)
		}
	default:
		printCommandHelp(command)
	}
	os.Exit(0)
}

func printTopicCommandsHelp(topic *Topic) {
	commands := topic.Commands()
	if len(commands) > 0 {
		Printf("\nCommands for %s, type \"heroku help %s:COMMAND\" for more details:\n\n", topic.Name, topic.Name)
		for _, command := range nonHiddenCommands(commands) {
			Printf(" heroku %-30s # %s\n", command.Usage, command.Description)
		}
	}
}

func printCommandHelp(command *Command) {
	Printf("Usage: heroku %s\n\n", command.Usage)
	Println(indent(command.buildFullHelp()))
}

func nonHiddenTopics(from []*Topic) []*Topic {
	to := make([]*Topic, 0, len(from))
	for _, topic := range from {
		if !topic.Hidden {
			to = append(to, topic)
		}
	}
	return to
}

func nonHiddenCommands(from []*Command) []*Command {
	to := make([]*Command, 0, len(from))
	for _, command := range from {
		if !command.Hidden {
			to = append(to, command)
		}
	}
	return to
}

func indent(s string) string {
	return " " + strings.Join(strings.Split(s, "\n"), "\n ")
}
<|endoftext|>


<commit_before>package main

import (
  "fmt"
  "flag"
  "bufio"
  "os"
  "log"
  "io/ioutil"
  "strings"
  "strconv"
  "net/http"
  "net/url"
)

type pt struct {
  sent float64
  recv float64
}

var data map[string]pt

func adddata(s string, p pt) {
  if _,ok := data[s]; ok {
    p2 := pt{data[s].sent + p.sent, data[s].recv+p.recv}
    data[s] = p2
  } else {
    data[s] = pt{0.0,0.0}
  }
}

func check(err error) {
  if err != nil {
    log.Fatal(err)
  }
}

//flags
var (
  filename,datatable string
  pprint bool
)

func main() {
  data = map[string]pt {}
  flag.StringVar(&datatable, "datatable", "", "Datatable server details")
  flag.BoolVar(&pprint, "prettyprint", false, "Pretty Print")
  flag.Parse()
  filename = flag.Args()[0]
  file, err := os.Open(filename)
  check(err)
  scanner := bufio.NewScanner(file)
  for scanner.Scan() {
    parseline(scanner.Text())
  }
  if err = scanner.Err(); err != nil {
    log.Fatal(err)
  }
  if pprint {
    prettyprint()
  }
  if datatable != "" {
    send_to_datatable()
  }
}

func parseline(line string) {
  l := strings.Fields(line)
  if len(l) < 3 { return }
  recv, err := strconv.ParseFloat(l[len(l)-1],64)
  if err != nil { return }
  sent, err := strconv.ParseFloat(l[len(l)-2],64)
  if err != nil { return }
  processCol := strings.Join(l[0:len(l)-2],"_")
  processdata := strings.Split(processCol, "/")
  if len(processdata) < 3 { return }
  pname := strings.Join(processdata[0:len(processdata)-2], "/")
  if strings.Index(pname, ":") != -1 && strings.Index(pname, "-") != -1 {
    pname = strings.Split(pname, "-")[0]
  }
  adddata(pname, pt{ sent, recv })
}

func prettyprint() {
  for proc, _ := range data {
    fmt.Printf("%40s\t%10.2f\t%10.2f\n", proc, data[proc].sent, data[proc].recv)
  }
}

func getcsv() string{
  csv := ""
  hostname,_ := os.Hostname()
  for proc, _ := range data {
    csv = csv + fmt.Sprintf("%s,%.2f,%.2f,%s,%s\n",
      proc, data[proc].sent, data[proc].recv,filename,hostname)
  }
  return csv
}

func send_to_datatable() {
  classname := "nethogs"
  hostname, _ := os.Hostname()
  params := url.Values{}
  params.Set("class", classname)
  params.Set("host", hostname)
  params.Set("data", getcsv())
  if strings.Index(datatable, "http://") != 0 {
    datatable = "http://" + datatable
  }
  resp, err := http.PostForm(datatable + "/api/put", params)
  check(err)
  defer resp.Body.Close()
  body, err := ioutil.ReadAll(resp.Body)
  check(err)
  fmt.Println(string(body))
}
<commit_msg>Some modifications and bug fixes<commit_after>package main

import (
  "fmt"
  "flag"
  "bufio"
  "os"
  "log"
  "io/ioutil"
  "os/user"
  "strings"
  "strconv"
  "net/http"
  "net/url"
)

type set map[string]struct{}

func (s set) add(x string) set {
  if s == nil {
    s = make(set)
  }
  s[x] = struct{}{}
  return s
}

func (s set) get() []string {
  x:=[]string{}
  for i := range s{
    x = append(x,i)
  }
  return x
}

type pt struct {
  sent float64
  recv float64
  users set
}

var data map[string]pt

func check(err error) {
  if err != nil {
    log.Fatal(err)
  }
}

//flags
var (
  filename,datatable string
  pprint bool
)

func main() {
  data = map[string]pt {}
  flag.StringVar(&datatable, "datatable", "", "Datatable server details")
  flag.BoolVar(&pprint, "pp", false, "Pretty Print")
  flag.Parse()
  filename = flag.Args()[0]
  file, err := os.Open(filename)
  check(err)
  scanner := bufio.NewScanner(file)
  for scanner.Scan() {
    parseline(scanner.Text())
  }
  if err = scanner.Err(); err != nil {
    log.Fatal(err)
  }
  if pprint {
    prettyprint()
  }
  if datatable != "" {
    send_to_datatable()
  }
}

func parseline(line string) {
  l := strings.Fields(line)
  if len(l) < 3 { return }
  recv, err := strconv.ParseFloat(l[len(l)-1],64)
  if err != nil { return }
  sent, err := strconv.ParseFloat(l[len(l)-2],64)
  if err != nil { return }
  processCol := strings.Join(l[0:len(l)-2],"_")
  processdata := strings.Split(processCol, "/")
  if len(processdata) < 3 { return }
  pname := strings.Join(processdata[0:len(processdata)-2], "/")
  if strings.Index(pname, ":") != -1 && strings.Index(pname, "-") != -1 {
    pname = strings.Split(pname, "-")[0]
  }
  ud, err := user.LookupId(processdata[len(processdata)-1])
  if err != nil {
    ud = &user.User { "-1", "-1", "dontknow", "dontknow", "/home/dontknow" }
  }
  data[pname] = pt{
    data[pname].sent + sent,
    data[pname].recv + recv,
    data[pname].users.add(ud.Username),
  }
}

func prettyprint() {
  for proc, _ := range data {
    fmt.Printf("%40s\t%10.2f\t%10.2f\t%40s\n", proc, data[proc].sent, data[proc].recv,
      strings.Join(data[proc].users.get(), ",") )
  }
}

func getcsv() string{
  csv := ""
  hostname,_ := os.Hostname()
  for proc, _ := range data {
    csv = csv + fmt.Sprintf("%s,%.2f,%.2f,%s,%s,%s\n",
      proc, data[proc].sent, data[proc].recv,
      strings.Join(data[proc].users.get(), " "),
      filename,hostname)
  }
  return csv
}

func send_to_datatable() {
  classname := "nethogs"
  hostname, _ := os.Hostname()
  params := url.Values{}
  params.Set("class", classname)
  params.Set("host", hostname)
  params.Set("data", getcsv())
  if strings.Index(datatable, "http://") != 0 {
    datatable = "http://" + datatable
  }
  resp, err := http.PostForm(datatable + "/api/put", params)
  check(err)
  defer resp.Body.Close()
  body, err := ioutil.ReadAll(resp.Body)
  check(err)
  fmt.Println(string(body))
}
<|endoftext|>


<commit_before>// Copyright (c) 2017 Che Wei, Lin
//
// 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 tinynet

import (
	"net"
	"path/filepath"

	"github.com/containernetworking/plugins/pkg/ip"
	"github.com/containernetworking/plugins/pkg/ns"
	log "github.com/sirupsen/logrus"
)

// Host is a host instance
type Host struct {
	NodeType string
	Name     string
	vethName string
	IfName   string
	Sandbox  string
	IP       string
	MAC      string
}

// NewHost for creating a network namespace
func NewHost(name string, docker bool) (*Host, error) {
	h := new(Host)
	h.NodeType = "Host"
	h.Name = name

	// Create a network namespace
	targetNs, err := ns.NewNS()
	if err != nil {
		log.Fatal("failed to open netns: ", err)
	}
	// log.Info("netns mouted into the host: ", targetNs.Path())
	log.Infof("Adding a host: %s, namespace: %s", h.Name, filepath.Base(targetNs.Path()))
	h.Sandbox = targetNs.Path()
	return h, nil
}

func NewContainer(name string, imageRef string) (*Host, error) {
	h := new(Host)
	h.NodeType = "Host"
	h.Name = name
	_, sandboxKey := ensureDocker(imageRef)
	h.Sandbox = sandboxKey
	log.Info("netns mouted into the host: ", h.Sandbox)
	return h, nil
}

func (h *Host) setupVeth(ifName string, mtu int) (*Host, error) {
	// Get network namespace object
	netns, err := ns.GetNS(h.Sandbox)
	if err != nil {
		log.Fatal("failed to open netns: ", err)
	}
	defer netns.Close()

	// attach network namespace and setup veth pair
	err = netns.Do(func(hostNS ns.NetNS) error {
		// create the veth pair in the container and move host end into host netns
		hostVeth, containerVeth, err := ip.SetupVeth(ifName, mtu, hostNS)
		if err != nil {
			return err
		}
		// Host interface name
		h.IfName = containerVeth.Name

		// h.mac = containerVeth.HardwareAddr.String()

		// Host veth name
		h.vethName = hostVeth.Name

		// ip link set lo up
		_, err = ifaceUp("lo")
		if err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		return nil, err
	}
	return h, nil
}

func (h *Host) setIfaceIP(address string) error {
	// Get network namespace object
	netns, err := ns.GetNS(h.Sandbox)
	if err != nil {
		log.Fatal("failed to open netns: ", err)
	}
	defer netns.Close()

	ipv4Addr, _, err := net.ParseCIDR(address)
	if err != nil {
		return err
	}
	h.IP = ipv4Addr.String()
	err = netns.Do(func(hostNS ns.NetNS) error {
		if err := setIP(h.IfName, address); err != nil {
			return err
		}
		// ip link set ifName up
		_, err := ifaceUp(h.IfName)
		if err != nil {
			return err
		}
		// get Host mac address
		hostIface, err := net.InterfaceByName(h.IfName)
		if err != nil {
			return err
		}
		h.MAC = hostIface.HardwareAddr.String()
		return nil
	})
	if err != nil {
		return err
	}
	return nil
}
<commit_msg>handle error<commit_after>// Copyright (c) 2017 Che Wei, Lin
//
// 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 tinynet

import (
	"net"
	"path/filepath"

	"github.com/containernetworking/plugins/pkg/ip"
	"github.com/containernetworking/plugins/pkg/ns"
	log "github.com/sirupsen/logrus"
)

// Host is a host instance
type Host struct {
	NodeType string
	Name     string
	vethName string
	IfName   string
	Sandbox  string
	IP       string
	MAC      string
}

// NewHost for creating a network namespace
func NewHost(name string, docker bool) (*Host, error) {
	h := new(Host)
	h.NodeType = "Host"
	h.Name = name

	// Create a network namespace
	targetNs, err := ns.NewNS()
	if err != nil {
		log.Fatal("failed to open netns: ", err)
		return nil, err
	}
	// log.Info("netns mouted into the host: ", targetNs.Path())
	log.Infof("Adding a host: %s, namespace: %s", h.Name, filepath.Base(targetNs.Path()))
	h.Sandbox = targetNs.Path()
	return h, nil
}

// NewContainer for creating a docker container
func NewContainer(name string, imageRef string) (*Host, error) {
	h := new(Host)
	h.NodeType = "Host"
	h.Name = name
	_, sandboxKey, err := ensureDocker(imageRef)
	if err != nil {
		log.Fatal("failed to start container: ", err)
		return nil, err
	}
	h.Sandbox = sandboxKey
	log.Info("netns mouted into the host: ", h.Sandbox)
	return h, nil
}

func (h *Host) setupVeth(ifName string, mtu int) (*Host, error) {
	// Get network namespace object
	netns, err := ns.GetNS(h.Sandbox)
	if err != nil {
		log.Fatal("failed to open netns: ", err)
	}
	defer netns.Close()

	// attach network namespace and setup veth pair
	err = netns.Do(func(hostNS ns.NetNS) error {
		// create the veth pair in the container and move host end into host netns
		hostVeth, containerVeth, err := ip.SetupVeth(ifName, mtu, hostNS)
		if err != nil {
			return err
		}
		// Host interface name
		h.IfName = containerVeth.Name

		// h.mac = containerVeth.HardwareAddr.String()

		// Host veth name
		h.vethName = hostVeth.Name

		// ip link set lo up
		_, err = ifaceUp("lo")
		if err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		return nil, err
	}
	return h, nil
}

func (h *Host) setIfaceIP(address string) error {
	// Get network namespace object
	netns, err := ns.GetNS(h.Sandbox)
	if err != nil {
		log.Fatal("failed to open netns: ", err)
	}
	defer netns.Close()

	ipv4Addr, _, err := net.ParseCIDR(address)
	if err != nil {
		return err
	}
	h.IP = ipv4Addr.String()
	err = netns.Do(func(hostNS ns.NetNS) error {
		if err := setIP(h.IfName, address); err != nil {
			return err
		}
		// ip link set ifName up
		_, err := ifaceUp(h.IfName)
		if err != nil {
			return err
		}
		// get Host mac address
		hostIface, err := net.InterfaceByName(h.IfName)
		if err != nil {
			return err
		}
		h.MAC = hostIface.HardwareAddr.String()
		return nil
	})
	if err != nil {
		return err
	}
	return nil
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"fmt"
)

func pageHTML(title string, content string) string {
	var html bytes.Buffer
	html.WriteString(`<!DOCTYPE html>

<title>`)
	html.WriteString(title)
	html.WriteString(`</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,400i,600,700" rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="/static/style.css">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">

			<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
			Toggle navigation

			</button>
			BookBrowser

Books

Authors

Series

Random Book

				<form class="navbar-form" role="search" method="GET" action="/search/">

					<input type="text" class="form-control" placeholder="Search" name="q" id="q">

						<button class="btn btn-default" type="submit"></button>

				</form>

`)
	html.WriteString(title)
	html.WriteString(`

`)
	html.WriteString(content)
	html.WriteString(`

BookBrowser ` + curversion + `

Copyright 2017 Patrick G

`)
	return html.String()
}

func bookHTML(b *Book, isCard bool) string {
	var html bytes.Buffer
	if isCard {
		html.WriteString(`<div class="book card">`)
	} else {
		html.WriteString(`<div class="book info">`)
	}

	html.WriteString(`<a class="cover" href="/books/` + b.ID + `">`)
	if b.HasCover {
		if isCard {
			html.WriteString(`<img alt="cover" src="/covers/` + b.ID + `_thumb.jpg" />`)
		} else {
			html.WriteString(`<img alt="cover" src="/covers/` + b.ID + `.jpg" />`)
		}
	} else {
		html.WriteString(`<img alt="cover" src="/static/nocover.jpg" />`)
	}
	html.WriteString(`</a>`)

	html.WriteString(`<div class="meta">`)
	html.WriteString(`<a class="title" href="/books/` + b.ID + `">`)
	html.WriteString(b.Title)
	html.WriteString(`</a>`)
	if b.Author != "" {
		html.WriteString(`<a class="author" href="/authors/` + b.AuthorID + `">`)
		html.WriteString(b.Author)
		html.WriteString(`</a>`)
	}
	if b.Series.Name != "" {
		html.WriteString(`<div class="series">`)
		html.WriteString(`<a class="name" href="/series/` + b.Series.ID + `">`)
		html.WriteString(b.Series.Name)
		html.WriteString(`</a> - <span class="index">`)
		html.WriteString(fmt.Sprintf("%v", b.Series.Index))
		html.WriteString(`</span>`)
		html.WriteString(`</div>`)
	}
	if !isCard && b.Description != "" {
		html.WriteString(`<div class="description">`)
		html.WriteString(b.Description)
		html.WriteString(`</div>`)
	}
	html.WriteString(`<a class="download btn btn-default" href="/download/` + b.ID + `.epub">Download EPUB</a>`)
	html.WriteString(`<a class="reader btn btn-default" href="/static/reader/#!/download/` + b.ID + `.epub">Read</a>`)
	html.WriteString(`</div>`)

	html.WriteString(`</div>`)
	return html.String()
}

func bookListPageHTML(books []Book, title string, notfoundtext string) (html string, notfound bool) {
	if len(books) == 0 {
		return pageHTML("Not Found", notfoundtext), true
	}

	var booksHTML bytes.Buffer
	booksHTML.WriteString(`<div class="books cards">`)
	for _, b := range books {
		booksHTML.WriteString(bookHTML(&b, true))
	}
	booksHTML.WriteString(`</div>`)

	return pageHTML(title, booksHTML.String()), false
}

func itemCardHTML(title string, description string, link string) string {
	var html bytes.Buffer
	html.WriteString(`<a class="item card" href="` + link + `">`)
	html.WriteString(`<div class="title">`)
	html.WriteString(title)
	html.WriteString(`</div>`)
	html.WriteString(`<div class="description">`)
	html.WriteString(description)
	html.WriteString(`</div>`)
	html.WriteString(`</a>`)
	return html.String()
}
<commit_msg>Only show read button for epub books<commit_after>package main

import (
	"bytes"
	"fmt"
	"strings"
)

func pageHTML(title string, content string) string {
	var html bytes.Buffer
	html.WriteString(`<!DOCTYPE html>

<title>`)
	html.WriteString(title)
	html.WriteString(`</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,400i,600,700" rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="/static/style.css">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">

			<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
			Toggle navigation

			</button>
			BookBrowser

Books

Authors

Series

Random Book

				<form class="navbar-form" role="search" method="GET" action="/search/">

					<input type="text" class="form-control" placeholder="Search" name="q" id="q">

						<button class="btn btn-default" type="submit"></button>

				</form>

`)
	html.WriteString(title)
	html.WriteString(`

`)
	html.WriteString(content)
	html.WriteString(`

BookBrowser ` + curversion + `

Copyright 2017 Patrick G

`)
	return html.String()
}

func bookHTML(b *Book, isCard bool) string {
	var html bytes.Buffer
	if isCard {
		html.WriteString(`<div class="book card">`)
	} else {
		html.WriteString(`<div class="book info">`)
	}

	html.WriteString(`<a class="cover" href="/books/` + b.ID + `">`)
	if b.HasCover {
		if isCard {
			html.WriteString(`<img alt="cover" src="/covers/` + b.ID + `_thumb.jpg" />`)
		} else {
			html.WriteString(`<img alt="cover" src="/covers/` + b.ID + `.jpg" />`)
		}
	} else {
		html.WriteString(`<img alt="cover" src="/static/nocover.jpg" />`)
	}
	html.WriteString(`</a>`)

	html.WriteString(`<div class="meta">`)
	html.WriteString(`<a class="title" href="/books/` + b.ID + `">`)
	html.WriteString(b.Title)
	html.WriteString(`</a>`)
	if b.Author != "" {
		html.WriteString(`<a class="author" href="/authors/` + b.AuthorID + `">`)
		html.WriteString(b.Author)
		html.WriteString(`</a>`)
	}
	if b.Series.Name != "" {
		html.WriteString(`<div class="series">`)
		html.WriteString(`<a class="name" href="/series/` + b.Series.ID + `">`)
		html.WriteString(b.Series.Name)
		html.WriteString(`</a> - <span class="index">`)
		html.WriteString(fmt.Sprintf("%v", b.Series.Index))
		html.WriteString(`</span>`)
		html.WriteString(`</div>`)
	}
	if !isCard && b.Description != "" {
		html.WriteString(`<div class="description">`)
		html.WriteString(b.Description)
		html.WriteString(`</div>`)
	}
	html.WriteString(`<a class="download btn btn-default" href="/download/` + b.ID + `.` + b.FileType + `">Download ` + strings.ToUpper(b.FileType) + `</a>`)
	if b.FileType == "epub" {
		html.WriteString(`<a class="reader btn btn-default" href="/static/reader/#!/download/` + b.ID + `.` + b.FileType + `">Read</a>`)
	}
	html.WriteString(`</div>`)

	html.WriteString(`</div>`)
	return html.String()
}

func bookListPageHTML(books []Book, title string, notfoundtext string) (html string, notfound bool) {
	if len(books) == 0 {
		return pageHTML("Not Found", notfoundtext), true
	}

	var booksHTML bytes.Buffer
	booksHTML.WriteString(`<div class="books cards">`)
	for _, b := range books {
		booksHTML.WriteString(bookHTML(&b, true))
	}
	booksHTML.WriteString(`</div>`)

	return pageHTML(title, booksHTML.String()), false
}

func itemCardHTML(title string, description string, link string) string {
	var html bytes.Buffer
	html.WriteString(`<a class="item card" href="` + link + `">`)
	html.WriteString(`<div class="title">`)
	html.WriteString(title)
	html.WriteString(`</div>`)
	html.WriteString(`<div class="description">`)
	html.WriteString(description)
	html.WriteString(`</div>`)
	html.WriteString(`</a>`)
	return html.String()
}
<|endoftext|>


<commit_before>package tcclient

import (
	"bytes"
	"crypto/sha256"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	// "net/http/httputil"
	"net/url"
	"reflect"
	"time"

	"github.com/taskcluster/httpbackoff"
	hawk "github.com/tent/hawk-go"
)

// CallSummary provides information about the underlying http request and
// response issued for a given API call.
type CallSummary struct {
	HTTPRequest *http.Request
	// Keep a copy of request body in addition to the *http.Request, since
	// accessing the Body via the *http.Request object, you get a io.ReadCloser
	// - and after the request has been made, the body will have been read, and
	// the data lost... This way, it is still available after the api call
	// returns.
	HTTPRequestBody string
	// The Go Type which is marshaled into json and used as the http request
	// body.
	HTTPRequestObject interface{}
	HTTPResponse      *http.Response
	// Keep a copy of response body in addition to the *http.Response, since
	// accessing the Body via the *http.Response object, you get a
	// io.ReadCloser - and after the response has been read once (to unmarshal
	// json into native go types) the data is lost... This way, it is still
	// available after the api call returns.
	HTTPResponseBody string
	// Keep a record of how many http requests were attempted
	Attempts int
}

type APICall struct {
	Client      *Client
	Route       string
	QueryString url.Values
	Payload     io.Reader
}

// DefaultHTTPClient is the HTTP Client used to make requests.
// A single object is created an used because http.Client is thread-safe when
// making multiple requests in various goroutines.
var DefaultHTTPClient = &http.Client{}

// utility function to create a URL object based on given data
func setURL(client *Client, route string, query url.Values) (u *url.URL, err error) {
	u, err = url.Parse(client.BaseURL + route)
	if err != nil {
		return nil, fmt.Errorf("Cannot parse url: '%v', is BaseURL (%v) set correctly?\n%v\n", client.BaseURL+route, client.BaseURL, err)
	}
	if query != nil {
		u.RawQuery = query.Encode()
	}
	return
}

// Request is the underlying method that makes a raw API request, without
// performing any json marshaling/unmarshaling of requests/responses. It is
// useful if you wish to handle raw payloads and/or raw http response bodies,
// rather than calling APICall which translates []byte to/from go types.
func (client *Client) Request(rawPayload []byte, method, route string, query url.Values) (*CallSummary, error) {
	callSummary := new(CallSummary)
	callSummary.HTTPRequestBody = string(rawPayload)

	// function to perform http request - we call this using backoff library to
	// have exponential backoff in case of intermittent failures (e.g. network
	// blips or HTTP 5xx errors)
	httpCall := func() (*http.Response, error, error) {
		var ioReader io.Reader
		ioReader = bytes.NewReader(rawPayload)
		u, err := setURL(client, route, query)
		if err != nil {
			return nil, nil, fmt.Errorf("apiCall url cannot be parsed:\n%v\n", err)
		}
		callSummary.HTTPRequest, err = http.NewRequest(method, u.String(), ioReader)
		if err != nil {
			return nil, nil, fmt.Errorf("Internal error: apiCall url cannot be parsed although thought to be valid: '%v', is the BaseURL (%v) set correctly?\n%v\n", u.String(), client.BaseURL, err)
		}
		callSummary.HTTPRequest.Header.Set("Content-Type", "application/json")
		// Refresh Authorization header with each call...
		// Only authenticate if client library user wishes to.
		if client.Authenticate {
			err = client.Credentials.SignRequest(callSummary.HTTPRequest)
			if err != nil {
				return nil, nil, err
			}
		}
		resp, err := DefaultHTTPClient.Do(callSummary.HTTPRequest)
		// b, e := httputil.DumpResponse(resp, true)
		// if e == nil {
		// 	fmt.Println(string(b))
		// }
		return resp, err, nil
	}

	// Make HTTP API calls using an exponential backoff algorithm...
	var err error
	callSummary.HTTPResponse, callSummary.Attempts, err = httpbackoff.Retry(httpCall)

	// read response into memory, so that we can return the body
	if callSummary.HTTPResponse != nil {
		body, err2 := ioutil.ReadAll(callSummary.HTTPResponse.Body)
		if err2 == nil {
			callSummary.HTTPResponseBody = string(body)
		}
	}

	return callSummary, err

}

// SignRequest will add an Authorization header
func (c *Credentials) SignRequest(req *http.Request) (err error) {
	// s, err := c.SignHeader(req.Method, req.URL.String(), hash)
	// req.Header.Set("Authorization", s)
	// return err

	credentials := &hawk.Credentials{
		ID:   c.ClientID,
		Key:  c.AccessToken,
		Hash: sha256.New,
	}
	reqAuth := hawk.NewRequestAuth(req, credentials, 0)
	reqAuth.Ext, err = getExtHeader(c)
	if err != nil {
		return fmt.Errorf("Internal error: was not able to generate hawk ext header from provided credentials:\n%s\n%s", c, err)
	}
	req.Header.Set("Authorization", reqAuth.RequestHeader())
	return nil
}

// APICall is the generic REST API calling method which performs all REST API
// calls for this library.  Each auto-generated REST API method simply is a
// wrapper around this method, calling it with specific specific arguments.
func (client *Client) APICall(payload interface{}, method, route string, result interface{}, query url.Values) (interface{}, *CallSummary, error) {
	rawPayload := []byte{}
	var err error
	if reflect.ValueOf(payload).IsValid() && !reflect.ValueOf(payload).IsNil() {
		rawPayload, err = json.Marshal(payload)
		if err != nil {
			return result, &CallSummary{HTTPRequestObject: payload}, err
		}
	}
	callSummary, err := client.Request(rawPayload, method, route, query)
	callSummary.HTTPRequestObject = payload
	if err != nil {
		return result, callSummary, err
	}
	// if result is passed in as nil, it means the API defines no response body
	// json
	if reflect.ValueOf(result).IsValid() && !reflect.ValueOf(result).IsNil() {
		err = json.Unmarshal([]byte(callSummary.HTTPResponseBody), &result)
	}

	return result, callSummary, err
}

// SignedURL creates a signed URL using the given Client, where route is the
// url path relative to the BaseURL stored in the Client, query is the set of
// query string parameters, if any, and duration is the amount of time that the
// signed URL should remain valid for.
func (client *Client) SignedURL(route string, query url.Values, duration time.Duration) (u *url.URL, err error) {
	u, err = setURL(client, route, query)
	if err != nil {
		return
	}
	credentials := &hawk.Credentials{
		ID:   client.Credentials.ClientID,
		Key:  client.Credentials.AccessToken,
		Hash: sha256.New,
	}
	reqAuth, err := hawk.NewURLAuth(u.String(), credentials, duration)
	if err != nil {
		return
	}
	reqAuth.Ext, err = getExtHeader(client.Credentials)
	if err != nil {
		return
	}
	bewitSignature := reqAuth.Bewit()
	if query == nil {
		query = url.Values{}
	}
	query.Set("bewit", bewitSignature)
	u.RawQuery = query.Encode()
	return
}

// getExtHeader generates the hawk ext header based on the authorizedScopes and
// the certificate used in the case of temporary credentials. The header is a
// base64 encoded json object with a "certificate" property set to the
// certificate of the temporary credentials and a "authorizedScopes" property
// set to the array of authorizedScopes, if provided.  If either "certificate"
// or "authorizedScopes" is not supplied, they will be omitted from the json
// result. If neither are provided, an empty string is returned, rather than a
// base64 encoded representation of "null" or "{}". Hawk interprets the empty
// string as meaning the ext header is not needed.
//
// See:
//   * https://docs.taskcluster.net/manual/apis/authorized-scopes
//   * https://docs.taskcluster.net/manual/apis/temporary-credentials
func getExtHeader(credentials *Credentials) (header string, err error) {
	ext := &ExtHeader{}
	if credentials.Certificate != "" {
		certObj := new(Certificate)
		err = json.Unmarshal([]byte(credentials.Certificate), certObj)
		if err != nil {
			return "", err
		}
		ext.Certificate = certObj
	}

	if credentials.AuthorizedScopes != nil {
		ext.AuthorizedScopes = &credentials.AuthorizedScopes
	}
	extJSON, err := json.Marshal(ext)
	if err != nil {
		return "", err
	}
	if string(extJSON) != "{}" {
		return base64.StdEncoding.EncodeToString(extJSON), nil
	}
	return "", nil
}

// ExtHeader represents the authentication/authorization data that is contained
// in the ext field inside the base64 decoded `Authorization` HTTP header in
// outgoing Hawk HTTP requests.
type ExtHeader struct {
	Certificate *Certificate `json:"certificate,omitempty"`
	// use pointer to slice to distinguish between nil slice and empty slice
	AuthorizedScopes *[]string `json:"authorizedScopes,omitempty"`
}
<commit_msg>Added mockable interface for http.Client<commit_after>package tcclient

import (
	"bytes"
	"crypto/sha256"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	// "net/http/httputil"
	"net/url"
	"reflect"
	"time"

	"github.com/taskcluster/httpbackoff"
	hawk "github.com/tent/hawk-go"
)

// CallSummary provides information about the underlying http request and
// response issued for a given API call.
type CallSummary struct {
	HTTPRequest *http.Request
	// Keep a copy of request body in addition to the *http.Request, since
	// accessing the Body via the *http.Request object, you get a io.ReadCloser
	// - and after the request has been made, the body will have been read, and
	// the data lost... This way, it is still available after the api call
	// returns.
	HTTPRequestBody string
	// The Go Type which is marshaled into json and used as the http request
	// body.
	HTTPRequestObject interface{}
	HTTPResponse      *http.Response
	// Keep a copy of response body in addition to the *http.Response, since
	// accessing the Body via the *http.Response object, you get a
	// io.ReadCloser - and after the response has been read once (to unmarshal
	// json into native go types) the data is lost... This way, it is still
	// available after the api call returns.
	HTTPResponseBody string
	// Keep a record of how many http requests were attempted
	Attempts int
}

type APICall struct {
	Client      *Client
	Route       string
	QueryString url.Values
	Payload     io.Reader
}

// ReducedHTTPClient is the interface that wraps the functionality of
// http.Client that we actually use in Client.APICall.
type ReducedHTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

// DefaultHTTPClient is the HTTP Client used to make requests.
// A single object is created an used because http.Client is thread-safe when
// making multiple requests in various goroutines.
var DefaultHTTPClient ReducedHTTPClient = &http.Client{}

// utility function to create a URL object based on given data
func setURL(client *Client, route string, query url.Values) (u *url.URL, err error) {
	u, err = url.Parse(client.BaseURL + route)
	if err != nil {
		return nil, fmt.Errorf("Cannot parse url: '%v', is BaseURL (%v) set correctly?\n%v\n", client.BaseURL+route, client.BaseURL, err)
	}
	if query != nil {
		u.RawQuery = query.Encode()
	}
	return
}

// Request is the underlying method that makes a raw API request, without
// performing any json marshaling/unmarshaling of requests/responses. It is
// useful if you wish to handle raw payloads and/or raw http response bodies,
// rather than calling APICall which translates []byte to/from go types.
func (client *Client) Request(rawPayload []byte, method, route string, query url.Values) (*CallSummary, error) {
	callSummary := new(CallSummary)
	callSummary.HTTPRequestBody = string(rawPayload)

	// function to perform http request - we call this using backoff library to
	// have exponential backoff in case of intermittent failures (e.g. network
	// blips or HTTP 5xx errors)
	httpCall := func() (*http.Response, error, error) {
		var ioReader io.Reader
		ioReader = bytes.NewReader(rawPayload)
		u, err := setURL(client, route, query)
		if err != nil {
			return nil, nil, fmt.Errorf("apiCall url cannot be parsed:\n%v\n", err)
		}
		callSummary.HTTPRequest, err = http.NewRequest(method, u.String(), ioReader)
		if err != nil {
			return nil, nil, fmt.Errorf("Internal error: apiCall url cannot be parsed although thought to be valid: '%v', is the BaseURL (%v) set correctly?\n%v\n", u.String(), client.BaseURL, err)
		}
		callSummary.HTTPRequest.Header.Set("Content-Type", "application/json")
		// Refresh Authorization header with each call...
		// Only authenticate if client library user wishes to.
		if client.Authenticate {
			err = client.Credentials.SignRequest(callSummary.HTTPRequest)
			if err != nil {
				return nil, nil, err
			}
		}
		resp, err := DefaultHTTPClient.Do(callSummary.HTTPRequest)
		// b, e := httputil.DumpResponse(resp, true)
		// if e == nil {
		// 	fmt.Println(string(b))
		// }
		return resp, err, nil
	}

	// Make HTTP API calls using an exponential backoff algorithm...
	var err error
	callSummary.HTTPResponse, callSummary.Attempts, err = httpbackoff.Retry(httpCall)

	// read response into memory, so that we can return the body
	if callSummary.HTTPResponse != nil {
		body, err2 := ioutil.ReadAll(callSummary.HTTPResponse.Body)
		if err2 == nil {
			callSummary.HTTPResponseBody = string(body)
		}
	}

	return callSummary, err

}

// SignRequest will add an Authorization header
func (c *Credentials) SignRequest(req *http.Request) (err error) {
	// s, err := c.SignHeader(req.Method, req.URL.String(), hash)
	// req.Header.Set("Authorization", s)
	// return err

	credentials := &hawk.Credentials{
		ID:   c.ClientID,
		Key:  c.AccessToken,
		Hash: sha256.New,
	}
	reqAuth := hawk.NewRequestAuth(req, credentials, 0)
	reqAuth.Ext, err = getExtHeader(c)
	if err != nil {
		return fmt.Errorf("Internal error: was not able to generate hawk ext header from provided credentials:\n%s\n%s", c, err)
	}
	req.Header.Set("Authorization", reqAuth.RequestHeader())
	return nil
}

// APICall is the generic REST API calling method which performs all REST API
// calls for this library.  Each auto-generated REST API method simply is a
// wrapper around this method, calling it with specific specific arguments.
func (client *Client) APICall(payload interface{}, method, route string, result interface{}, query url.Values) (interface{}, *CallSummary, error) {
	rawPayload := []byte{}
	var err error
	if reflect.ValueOf(payload).IsValid() && !reflect.ValueOf(payload).IsNil() {
		rawPayload, err = json.Marshal(payload)
		if err != nil {
			return result, &CallSummary{HTTPRequestObject: payload}, err
		}
	}
	callSummary, err := client.Request(rawPayload, method, route, query)
	callSummary.HTTPRequestObject = payload
	if err != nil {
		return result, callSummary, err
	}
	// if result is passed in as nil, it means the API defines no response body
	// json
	if reflect.ValueOf(result).IsValid() && !reflect.ValueOf(result).IsNil() {
		err = json.Unmarshal([]byte(callSummary.HTTPResponseBody), &result)
	}

	return result, callSummary, err
}

// SignedURL creates a signed URL using the given Client, where route is the
// url path relative to the BaseURL stored in the Client, query is the set of
// query string parameters, if any, and duration is the amount of time that the
// signed URL should remain valid for.
func (client *Client) SignedURL(route string, query url.Values, duration time.Duration) (u *url.URL, err error) {
	u, err = setURL(client, route, query)
	if err != nil {
		return
	}
	credentials := &hawk.Credentials{
		ID:   client.Credentials.ClientID,
		Key:  client.Credentials.AccessToken,
		Hash: sha256.New,
	}
	reqAuth, err := hawk.NewURLAuth(u.String(), credentials, duration)
	if err != nil {
		return
	}
	reqAuth.Ext, err = getExtHeader(client.Credentials)
	if err != nil {
		return
	}
	bewitSignature := reqAuth.Bewit()
	if query == nil {
		query = url.Values{}
	}
	query.Set("bewit", bewitSignature)
	u.RawQuery = query.Encode()
	return
}

// getExtHeader generates the hawk ext header based on the authorizedScopes and
// the certificate used in the case of temporary credentials. The header is a
// base64 encoded json object with a "certificate" property set to the
// certificate of the temporary credentials and a "authorizedScopes" property
// set to the array of authorizedScopes, if provided.  If either "certificate"
// or "authorizedScopes" is not supplied, they will be omitted from the json
// result. If neither are provided, an empty string is returned, rather than a
// base64 encoded representation of "null" or "{}". Hawk interprets the empty
// string as meaning the ext header is not needed.
//
// See:
//   * https://docs.taskcluster.net/manual/apis/authorized-scopes
//   * https://docs.taskcluster.net/manual/apis/temporary-credentials
func getExtHeader(credentials *Credentials) (header string, err error) {
	ext := &ExtHeader{}
	if credentials.Certificate != "" {
		certObj := new(Certificate)
		err = json.Unmarshal([]byte(credentials.Certificate), certObj)
		if err != nil {
			return "", err
		}
		ext.Certificate = certObj
	}

	if credentials.AuthorizedScopes != nil {
		ext.AuthorizedScopes = &credentials.AuthorizedScopes
	}
	extJSON, err := json.Marshal(ext)
	if err != nil {
		return "", err
	}
	if string(extJSON) != "{}" {
		return base64.StdEncoding.EncodeToString(extJSON), nil
	}
	return "", nil
}

// ExtHeader represents the authentication/authorization data that is contained
// in the ext field inside the base64 decoded `Authorization` HTTP header in
// outgoing Hawk HTTP requests.
type ExtHeader struct {
	Certificate *Certificate `json:"certificate,omitempty"`
	// use pointer to slice to distinguish between nil slice and empty slice
	AuthorizedScopes *[]string `json:"authorizedScopes,omitempty"`
}
<|endoftext|>


<commit_before>package main

import (
	"log"
	"time"
	"strconv"

	"net/http"
	"encoding/json"

	"github.com/gorilla/schema"
	"github.com/gorilla/mux"

	_ "github.com/lib/pq"
    // "github.com/coopernurse/gorp"
    "github.com/go-gorp/gorp"
)

var (
	// Recommended as package variable
	// on http://www.gorillatoolkit.org/pkg/schema
	decoder = schema.NewDecoder()
	// HTTP header defaults
	HEADER_DEFAULTS = map[string]string {
		"Access-Control-Allow-Origin": "*",
		"Content-Type": "application/json",
	}
)

func listenToRequests(dbmap *gorp.DbMap) {
	router := mux.NewRouter()

	router.HandleFunc("/amounts", func(res http.ResponseWriter, req *http.Request) {
		// date parameters
		// vars := mux.Vars(req)
		from, _ := strconv.Atoi(req.FormValue("from"))
		to, _ := strconv.Atoi(req.FormValue("to"))
		var amounts []Amounts

		// return all
		if from ==0 || to == 0 {
    		_, err := dbmap.Select(&amounts, "select * from amounts order by id")
    		Respond(amounts, err, res)
    		return
		}

		// otherwise get range
		_, err := dbmap.Select(&amounts, "select * from amounts where created > $1 and created < $2 order by id", from, to)
    	Respond(amounts, err, res)
    	return
    }).Methods("GET")

    http.Handle("/", router)
    log.Println("Listening on port 8080...")
    http.ListenAndServe(":8080", nil)
}

func SetHeaders(res http.ResponseWriter, code int) {
  	for k, v := range HEADER_DEFAULTS {
  		res.Header().Set(k, v)
  	}
  	res.Header().Set("Status", http.StatusText(code))
	res.Header().Set("Date", time.Now().String())
}

func Respond(i interface{}, err error, res http.ResponseWriter) {
	if err != nil {
		SetHeaders(res, 400)
		http.Error(res, err.Error(), http.StatusInternalServerError)
		return
	}

	js, err2 := json.Marshal(i)
	if err2 != nil {
		SetHeaders(res, 400)
		http.Error(res, err2.Error(), http.StatusInternalServerError)
		return
	}

	SetHeaders(res, 200)
	res.Write(js)
}<commit_msg>flaws<commit_after>package main

import (
	"log"
	"time"
	"strconv"

	"net/http"
	"encoding/json"

	"github.com/gorilla/schema"
	"github.com/gorilla/mux"

	_ "github.com/lib/pq"
    // "github.com/coopernurse/gorp"
    "github.com/go-gorp/gorp"
)

var (
	// Recommended as package variable
	// on http://www.gorillatoolkit.org/pkg/schema
	decoder = schema.NewDecoder()
	// HTTP header defaults
	HEADER_DEFAULTS = map[string]string {
		"Access-Control-Allow-Origin": "*",
		"Content-Type": "application/json",
	}
)

func listenToRequests(dbmap *gorp.DbMap) {
	router := mux.NewRouter()

	router.HandleFunc("/amounts", func(res http.ResponseWriter, req *http.Request) {
		// date parameters
		// vars := mux.Vars(req)
		from, _ := strconv.Atoi(req.FormValue("from"))
		to, _ := strconv.Atoi(req.FormValue("to"))
		var amounts []Amounts

		// return all
		if from ==0 || to == 0 {
    		_, err := dbmap.Select(&amounts, "select * from amounts order by id")
    		Respond(combineAmounts(amounts), err, res)
    		return
		}

		// otherwise get range
		_, err := dbmap.Select(&amounts, "select * from amounts where created > $1 and created < $2 order by id", from, to)
    	Respond(combineAmounts(amounts), err, res)
    	return
    }).Methods("GET")

    http.Handle("/", router)
    log.Println("Listening on port 8080...")
    http.ListenAndServe(":8080", nil)
}

func combineMaps(amounts []Amounts) {
	// aggregate := make(map[string]int)
	m := make(map[string]int)

	for a := range amounts {
		// get map
		byt := []byte(a.Json)
		if err := json.Unmarshal(byt, &dat); err != nil {
	        panic(err)
	    }

	    log.Println(m)
	}
}

func SetHeaders(res http.ResponseWriter, code int) {
  	for k, v := range HEADER_DEFAULTS {
  		res.Header().Set(k, v)
  	}
  	res.Header().Set("Status", http.StatusText(code))
	res.Header().Set("Date", time.Now().String())
}

func Respond(i interface{}, err error, res http.ResponseWriter) {
	if err != nil {
		SetHeaders(res, 400)
		http.Error(res, err.Error(), http.StatusInternalServerError)
		return
	}

	js, err2 := json.Marshal(i)
	if err2 != nil {
		SetHeaders(res, 400)
		http.Error(res, err2.Error(), http.StatusInternalServerError)
		return
	}

	SetHeaders(res, 200)
	res.Write(js)
}<|endoftext|>