Go
Introduction
Installation
The simplest way to get the latest version of go is to download it from https://golang.org/dl/. Extract the package to /usr/local/go
and then set the following environment variables:
$ export PATH=$PATH:/usr/local/go/bin
$ export GOPATH=$HOME/go
Packages
You can get go packages using the go get
command. This will download it to your $GOPATH/src
directory. In order to use the package, you will also need to build it by using the go build
command.
Eg:
$ go get github.com/miekg/dns
$ go build github.com/miekg/dns
Simple Program
Create your program in $GOPATH/src/
, ideally under a unique namespace. To build, run go build
followed by your namespace and program name. If it compiles properly, the program will be placed in the current working directory.
Packages
github.com/davecgh/go-spew/spew
Spew allows us to view structs and slices cleanly formatted in our console. This is nice to have.
Use with spew.Dump(Objout)
to dump the entire object out. Similar to dd()
in Laravel.
github.com/gorilla/mux
Gorilla/mux is a popular package for writing web handlers.
Use by creating a new router using mux.NewRouter()
, then assigning functions to different routes with mux.HandleFunc("/route", RouteHandlerFunc)
.
func run() {
muxRouter := mux.NewRouter()
muxRouter.HandleFunc("/", handleGet).Methods("GET")
muxRouter.HandleFunc("/", handlePost).Methods("POST")
s := &http.Server{
Addr: ":" + httpPort,
Handler: muxRouter ,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
if err := s.ListenAndServe(); err != nil {
log.Fatal(err)
}
}
func handleGet(w http.ResponseWriter, r *http.Request) {
bytes, err := json.MarshalIndent(Objout, "", " ")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
io.WriteString(w, string(bytes))
}
github.com/joho/godotenv
Godotenv lets us read from a .env file that we keep in the root of our directory so we don’t have to hardcode things like our http ports.
Use by first loading with godotenv.Load()
. Then use os.Getenv("XXX")
to get the value.
func main() {
err := godotenv.Load()
if err != nil {
log.Fatal(err)
}
httpPort := os.Getenv("PORT")
}
Resources
Play with golang online.
Guides
- https://tour.golang.org/
- https://golang.org/doc/effective_go.html
- https://github.com/a8m/go-lang-cheat-sheet
Quick Overview
TBD