Skip to content

Instantly share code, notes, and snippets.

@mtibben
Last active February 6, 2018 19:59
Show Gist options
  • Save mtibben/e013f591032487a8158c8ecc274f8a64 to your computer and use it in GitHub Desktop.
Save mtibben/e013f591032487a8158c8ecc274f8a64 to your computer and use it in GitHub Desktop.
Tibbo's go workshop
package main
import (
"bytes"
"encoding/json"
"fmt"
"html"
"html/template"
"io/ioutil"
"log"
"net/http"
"os"
)
type Person struct {
FirstName string `json:"firstname"`
LastName string `json:"lastname"`
}
func getJSONFromURL(url string) []byte {
resp, err := http.Get(url)
if err != nil {
log.Fatal(err)
}
json, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
return json
}
func getUsers() []byte {
return getJSONFromURL("https://jsonplaceholder.typicode.com/users")
}
func getPosts() []byte {
return getJSONFromURL("https://jsonplaceholder.typicode.com/posts")
}
func main() {
http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, world")
})
http.HandleFunc("/hello/url", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
})
http.HandleFunc("/hello/person", func(w http.ResponseWriter, r *http.Request) {
// w.Header().Add("X-XSS-Protection", "1")
fmt.Fprintf(w, "<html><body>")
fmt.Fprintf(w, "Hello, %s", r.URL.Query().Get("name"))
// fmt.Fprintf(w, "Hello, %s", html.EscapeString(r.URL.Query().Get("name")))
fmt.Fprintf(w, "</body></html>")
})
http.HandleFunc("/hello/template", func(w http.ResponseWriter, r *http.Request) {
t, err := template.New("T").Parse(`
Hello, {{ .FirstName }}
`)
if err != nil {
log.Fatal(err)
}
out := bytes.NewBufferString("")
t.Execute(out, struct {
FirstName string
LastName string
}{
FirstName: r.URL.Query().Get("firstname"),
LastName: r.URL.Query().Get("lastname"),
})
w.Write(out.Bytes())
})
http.HandleFunc("/hello/json", func(w http.ResponseWriter, r *http.Request) {
h := Person{
FirstName: r.URL.Query().Get("firstname"),
LastName: r.URL.Query().Get("lastname"),
}
in, err := json.Marshal(h)
if err != nil {
log.Fatal(err)
}
var out bytes.Buffer
err = json.Indent(&out, in, "", " ")
if err != nil {
log.Fatal(err)
}
// _, err = w.Write(out.Bytes())
_, err = out.WriteTo(w)
if err != nil {
log.Fatal(err)
}
})
http.HandleFunc("/hello/goroutine", func(w http.ResponseWriter, r *http.Request) {
usersChan := make(chan []byte)
postsChan := make(chan []byte)
go func(usersChan chan []byte) {
usersChan <- getUsers()
}(usersChan)
go func(postsChan chan []byte) {
postsChan <- getPosts()
}(postsChan)
users := <-usersChan
posts := <-postsChan
// users := getUsers()
// posts := getPosts()
w.Write(users)
w.Write(posts)
})
err := http.ListenAndServe(fmt.Sprintf(":%s", os.Getenv("PORT")), nil)
log.Fatal(err)
}

Tibbo's Go Workshop

Why Go

  • it's fast
  • code is simple, easy to maintain
    • no classes
    • no inheritence
    • no constructors
    • no generics
    • no exceptions
  • statically typed system, yet "feels" dynamic with inferred types
  • concurrency
  • toolchain
    • testing, linting, compiling, docs, packaging, installing
  • std library
  • deployment

The standard library


net/http


html/template


net/json

JSON is a string representation of a data structure. To Marshal or Encode is to serialise a data structure in to a JSON string. To Unmarshal or Decode is to convert a JSON string to a specified data structure. JSON itself in Go is represented by []byte instead of string though


goroutines

  • N:M threading model with coroutines/goroutines, compare to single threaded JS/PHP and threads in Ruby
  • channels are a typed conduit to send and recieve values

https://tour.golang.org/concurrency/1


More resources

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment