Skip to content

Instantly share code, notes, and snippets.

@edvakf edvakf/go.md
Last active Jun 28, 2017

Embed
What would you like to do?

golang使いまわせる処理一覧

md5

func md5hash(text []byte) string {
	h := md5.New()
	h.Write(text)
	return fmt.Sprintf("%x", h.Sum(nil))
}

gzip

func gzipEncode(text []byte) ([]byte, error) {
	b := new(bytes.Buffer)
	w := gzip.NewWriter(b)
	_, err := w.Write(text)
	if err != nil {
		return nil, err
	}
	w.Close()
	return b.Bytes(), nil
}

func gzipDecode(gz []byte) ([]byte, error) {
	b := bytes.NewReader(gz)
	r, err := gzip.NewReader(b)
	if err != nil {
		return nil, err
	}
	defer r.Close()
	text, err := ioutil.ReadAll(r)
	if err != nil {
		return nil, err
	}
	return text, nil
}

外部コマンドに標準入力から書いて標準出力の結果を得る

func runCmdWriteRead(command string, input []byte) ([]byte, error) {
	cmd := exec.Command(command)
	in, err := cmd.StdinPipe()
	if err != nil {
		return nil, err
	}
	out, err := cmd.StdoutPipe()
	if err != nil {
		return nil, err
	}

	err = cmd.Start()
	if err != nil {
		return nil, err
	}

	_, err = in.Write(input)
	if err != nil {
		return nil, err
	}

	in.Close()
	output, err := ioutil.ReadAll(out)
	if err != nil {
		return nil, err
	}

	cmd.Wait()
	return output, nil
}

gob

func gobEncode(obj interface{}) ([]byte, error) {
	b := &bytes.Buffer{}

	enc := gob.NewEncoder(b)
	err := enc.Encode(obj)
	if err != nil {
		return nil, err
	}

	return b.Bytes(), nil
}

func gobDecode(s []byte, obj *デコードしたい構造体) error {
	in := bytes.NewBuffer(s)
	dec := gob.NewDecoder(in)
	err := dec.Decode(&obj)
	return err
}

UNIX socketでlisten

var port = flag.Uint("port", 0, "port to listen")

...

func main() {
	flag.Parse()

	...

	sigchan := make(chan os.Signal)
	signal.Notify(sigchan, os.Interrupt)
	signal.Notify(sigchan, syscall.SIGTERM)
	signal.Notify(sigchan, syscall.SIGINT)

	var l net.Listener
	if *port == 0 {
		ferr := os.Remove("/tmp/server.sock")
		if ferr != nil {
			if !os.IsNotExist(ferr) {
				panic(ferr.Error())
			}
		}
		l, err = net.Listen("unix", "/tmp/server.sock")
		os.Chmod("/tmp/server.sock", 0777)
	} else {
		l, err = net.ListenTCP("tcp", &net.TCPAddr{Port: int(*port)})
	}
	if err != nil {
		panic(err.Error())
	}
	go func() {
		log.Println(http.Serve(l, nil))
	}()

	<-sigchan
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.