Go

From Leo's Notes
Last edited on 21 February 2022, at 22:18.

Introduction[edit | edit source]

Installation[edit | edit source]

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[edit | edit source]

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[edit | edit source]

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[edit | edit source]

github.com/davecgh/go-spew/spew[edit | edit source]

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[edit | edit source]

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[edit | edit source]

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[edit | edit source]

Play with golang online.

Guides

Quick Overview[edit | edit source]

TBD