0% found this document useful (0 votes)
142 views

Golang Cheatsheet v1

The document provides information about the Golang programming language. It covers topics like installing Golang, building and running Golang applications, using the Gorilla Mux HTTP router library, defining Golang structs and functions, working with goroutines and channels, handling errors, and using reflection. The cheat sheet also lists common Golang commands.

Uploaded by

Do Hoang
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
142 views

Golang Cheatsheet v1

The document provides information about the Golang programming language. It covers topics like installing Golang, building and running Golang applications, using the Gorilla Mux HTTP router library, defining Golang structs and functions, working with goroutines and channels, handling errors, and using reflection. The cheat sheet also lists common Golang commands.

Uploaded by

Do Hoang
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Pragmatic Reviews® • [email protected] • pragmaticreviews.

com
Golang :: CHEAT SHEET

Installing Golang Go commands Golang Interfaces


Linux Complete go command list Sample Interface

1.- Go to golang.org/dl bug start a bug report type PostRepository interface {


2.- Download the installer file build compile packages and dependencies Save(post *entity.Post) (*entity.Post, error)
3.- $ sudo tar -C /usr/local -xzf go1.13.5.linux- clean remove object files and cached files ...
amd64.tar.gz doc show documentation for package or }
4.- $ vim ~/.profile symbol
5.- Append :/usr/local/go/bin to the PATH env print Go environment information How to implement an Interface
environment variable. fix update packages to use new APIs
fmt gofmt (reformat) package sources
Building & running Golang apps generate generate Go files by processing source type repo struct{}
get add dependencies and install them
$ go build install compile and install //NewPostRepository creates a new repo
$ go run *.go packages/dependencies func NewPostRepository() PostRepository {
list list packages or modules return &repo{}
mod module maintenance }
Mux HTTP Router run compile and run Go program
test test packages func (*repo) Save(post *entity.Post) (*entity.Post,
 Package gorilla/mux implements a request tool run specified go tool error) {
router and dispatcher for matching incoming version print Go version ...
requests to their respective handler.
 Requests can be matched based on URL host, vet report likely mistakes in packages }
path, path prefix, schemes, header and query
values, HTTP methods or using custom
matchers. Golang Structs Goroutines
 URL hosts, paths and query values can have
variables with an optional regular expression. type Author struct {  Goroutines are lightweight threads (managed
ID int64 `json:"id"` by Go, not O.S. threads).
How to install Mux firstName string `json:"firstname"`  go f(a, b) starts a new goroutine which runs f.
fastName string `json:"lastname"`
$ go get github.com/gorilla/mux }
// Just a function (can be used as a goroutine)
How to use Mux type Post struct { func doStuff(s string) {
ID int64 `json:"id"` }
// Import the Mux library title string `json:"title"`
import "github.com/gorilla/mux" text string `json:"text"` func main() {
// Create a new Mux router instance author Author // using a named function in a goroutine
router := mux.NewRouter() } go doStuff("foobar")
// Handle HTTP requests
router.HandleFunc("/", func(w // using an anonymous inner function in a
http.ResponseWriter, r *http.Request) { Golang Functions goroutine
fmt.Fprintln(w, "Up and running...") go func (x int) {
}).Methods(“GET”) func add(x int, y int) int { // function body goes here
// Start the HTTP server listening on port 8080 return x + y }(42)
http.ListenAndServe(“:8080”, router) } }

Pragmatic Reviews® • [email protected] • pragmaticreviews.com


Golang :: CHEAT SHEET

Golang Channels Errors in Golang Reflection in Golang


ch := make(chan int) //create a channel of type int  There is no exception handling. Type Switch
ch <- 42 // Send a value to the channel ch.  Functions that might produce an error just
 A type switch is like a regular switch
v := <-ch // Receive a value from ch declare an additional return value of type Error.
statement, but the cases in a type switch
Error Interface specify types (not values), and those values
// Sending to a nil channel blocks forever are compared against the type of the value
var ch chan string held by the given interface value.
ch <- "Blocks!!!" type error interface {
// fatal error: all goroutines are asleep - deadlock! Error() string
}
func doIt(val interface{}) {
// Receiving from a nil channel blocks forever
switch v := val.(type) {
var ch chan string A function that may return an error
case int:
fmt.Println(<-ch)
func doSomething() (int, error) { fmt.Printf("Twice %v is %v\n", v, v*2)
// fatal error: all goroutines are asleep - deadlock!
} case string:
// Sending to a closed channel panics fmt.Printf("%q is %v bytes long\n", v, len(v))
var ch = make(chan string, 1) func main() { default:
ch <- "Hello, Open channel!" result, err := doSomething() fmt.Printf("I don't know about type %T!\n", v)
close(ch) if err != nil { }
ch <- "Hello, Closed channel!" // handle error }
// panic: send on closed channel } else {
// no errors, use result func main() {
// Receiving from a closed channel returns zero } doIt(88)
value immediately } doIt("a string")
var ch = make(chan int, 2) doIt(false)
ch <- 1 }
ch <- 2 Maps in Golang
close(ch)
for i := 0; i < 3; i++ { var m map[string]int Arrays/Slices in Golang
fmt.Printf("%d ", <-ch) m = make(map[string]int)
} m["key"] = 42 var a [10]int // declare an int array with length 10.
// 1 2 0 fmt.Println(m["key"]) Array length is part of the type!
delete(m, "key") a[3] = 42 // set elements
i := a[3] // read elements
elem, ok := m["key"] // test if key "key" is present
Golang Pointers and retrieve it, if so var a []int // declare a slice - similar to an array,
// map literal but length is unspecified
p := Point{1, 2} // p is a Point var m = map[string]Vertex{ var a = []int {1, 2, 3, 4} // declare and initialize a
q := &p // q is a pointer to a Point "Bell Labs": {40.68433, -74.39967}, slice (backed by the array given implicitly)
r := &Point{1, 2} // r is also a pointer to a Point "Google": {37.42202, -122.08408}, a := []int{1, 2, 3, 4} // shorthand
// The type of a pointer to a Point is *Point } chars := []string{0:"a", 2:"c", 1: "b"} // ["a", "b",
var s *Point = new(Point) // new creates a pointer // iterate over map content "c"]
to a new struct instance for key, value := range m {
}

Pragmatic Reviews® • [email protected] • pragmaticreviews.com

You might also like