Skip to content

Instantly share code, notes, and snippets.

@Raffo
Last active January 17, 2019 14:35
Show Gist options
  • Save Raffo/b8e96dd857c6c2c2b0555c741f465752 to your computer and use it in GitHub Desktop.
Save Raffo/b8e96dd857c6c2c2b0555c741f465752 to your computer and use it in GitHub Desktop.
Go tips

When your autocompletion is broken, it's probably because of gocode. Try:

gocode set autobuild true
(Close Atom and Sublime)
gocode drop-cache
gocode close
atom .

Make your test red/green, use:

https://github.com/rakyll/gotest

orpipe this:

| sed ''/PASS/s//$(printf "\033[32mPASS\033[0m")/'' | sed ''/FAIL/s//$(printf "\033[31mFAIL\033[0m")/''

Run an individual test

go test packageName -run TestName

Clean your GOPATH by removing all the things apart from some "protected" orgs and repos:

package main

import (
	"fmt"
	"io/ioutil"
	"os"
)

func contains(s []string, e string) bool {
	for _, a := range s {
		if a == e {
			return true
		}
	}
	return false
}

func main() {
	protectedOrgs := []string{"zalando", "zalando-stups", "Raffo", "teapot", "test", "tests", "zalando-incubator"}
	protectedSources := []string{"github.bus.zalan.do", "k8s.io", "test", "tests", "interviews", "gists"}

	goPath := os.Getenv("GOPATH")
	if goPath == "" {
		panic("GOPATH not set, cowardly refusing to do anything.")
	}
	//for now this is only a plan :-)
	files, _ := ioutil.ReadDir(fmt.Sprintf("%s/src", goPath))
	for _, f := range files {
		ff := fmt.Sprintf("%s/src/%s", goPath, f.Name())
		if !contains(protectedSources, f.Name()) {
			fmt.Println(ff)
		}
		a, _ := ioutil.ReadDir(ff)
		for _, b := range a {
			fff := b.Name()
			if !contains(protectedOrgs, fff) {
				fmt.Printf("\t%s\n", fff)
				os.RemoveAll(fmt.Sprintf("%s/src/%s/%s", goPath, f.Name(), fff))
				//fmt.Println(err)
			}
		}
	}
}

Find unused code in Go:

# Install the tool: 
go get honnef.co/go/tools/cmd/unused
unused $(go list github.com/teapot/clm/... | grep -v /vendor/)

Statick check of your code:

staticcheck $(go list  github.com/teapot/clm/... | grep -v /vendor/)

Testing http handlers:

 +	req, err := http.NewRequest("POST", "/foo", strings.NewReader(suite.EList))
 +	suite.Require().NoError(err)
 +
 +	// setup the test to record the response.
 +	rr := httptest.NewRecorder()
 +	suite.server.ServeHTTP(rr, req)
 +
 +	// assert that the status code is success.
 +	suite.Equal(http.StatusOK, rr.Code)
 +
 +	suite.Require().Len(suite.storage, 2)
 +	suite.Equal(suite.testEventA, suite.storage[0])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment