Run
go run myapp.go
Compile:
go build myapp.go
package main
import ("fmt")
func main() {
fmt.Println("Hello World")
}
Note: package main
= compiles to executable file.
func HandleLambdaEvent(event MyEvent) (MyResponse, error) {
return MyResponse{Message: fmt.Sprintf("%s is %d years old!", event.Name, event.Age)}, nil
}
Note: returns multiple values (MyResponse, error
).
import (
"package1"
p2 "package2"
)
go doc fmt
go doc fmt.Println
You define your module my_app
in go.mod
, then you can reference subfolders e.g. import "my_app/internal/pkg/db"
go vet main.go
go fmt main.go
gofmt -w main.go
var firstName string
var age int8 // int8-64, uint8-64
var percentageWater float = 0.70
var isHuman bool = false
const earthsGravity = 9.80665
type Album struct {
ID string `json:"id"`
Title string `json:"title"`
Artist string `json:"artist"`
Price float64 `json:"price"`
}
// albums slice to seed record album data.
var albums = [] album {
{ID: "1", Title: "Blue Train", Artist: "John Coltrane", Price: 56.99},
{ID: "2", Title: "Jeru", Artist: "Gerry Mulligan", Price: 17.99},
{ID: "3", Title: "Sarah Vaughan and Clifford Brown", Artist: "Sarah Vaughan", Price: 39.99},
}
type AlbumInterface interface {
ID string
Title string
Artist string
Price float64
}
privateFunction
PublicFunction
myVariable := aFunction()
stringBody, _ := json.Marshal(body)
This just ignores the second value.
Tags: https://medium.com/golangspec/tags-in-golang-3e5db0b8ef3e
user.Tag.Lookup("json")
os.Getenv("FOO")
os.Setenv("FOO", "1")
os.Environ()
https://gobyexample.com/command-line-flags
Unmarshal
= Parse
body := BodyParameters{}
json.Unmarshal([]byte(req.Body), &body)
Marshal
= Format as string
data, error := json.Marshal(pigeon)
fmt.Println(string(data))
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/hello-world", func(w http.ResponseWriter, r *http.Request){
fmt.Fprintf(w, "Hello world") // or: fmt.Fprint(w, myFunction())
})
http.ListenAndServe(":80", nil)
}