HTTP Handlers
package main
import (
"encoding/json"
"io"
"net/http"
)
func main() {
h := Handler{}
mux := http.NewServeMux()
mux.HandleFunc("POST /", h.Post)
mux.HandleFunc("GET /{id}", h.Get)
err := http.ListenAndServe(":8080", mux)
if err != nil {
panic(err)
}
}
type Handler struct{}
func (h Handler) Post(w http.ResponseWriter, r *http.Request) {
b, err := io.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
var body PostBody
if err := json.Unmarshal(b, &body); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
_, _ = w.Write(b)
}
func (h Handler) Get(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
data := GetResponse{
Name: id,
}
b, err := json.Marshal(data)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
_, _ = w.Write(b)
}
type PostBody struct {
Name string `json:"name"`
}
type GetResponse struct {
Name string `json:"name"`
}
Json Marshal
data := Body{
Name: id,
}
b, err := json.Marshal(data)Json Unmarshal
body, _ := io.ReadAll(r.Body)
var data Request
err := json.Unmarshal(body, &data)Pop from queue - first
x, a = a[0], a[1:]Pop from stack - last
x, a = a[len(a)-1], a[:len(a)-1]Push
a = append(a, x)Copy
s1 := []int{1, 2, 3, 4, 5}
s2 := append([]int{}, s1...)
// or
s1 := []int{1, 2, 3, 4, 5}
s2 := make([]int, len(s1))
_ = copy(s2, s1) // s2 is now an independent copy of s1Sync Package
WaitGroup - Go() or Add() and Done()
Map
Mutex
Close channel
For Select
for {
select {
case c <- x:
x, y = y, x+y
case <-quit:
fmt.Println("quit")
return
}
default:
time.Sleep(50 * time.Millisecond)
}// Create a type.
type Something string
// Create an alias.
type Something = stringgo clean -cache -testcache
go tool cover -html=coverage.txt
go test -v -count=1 -race -p 1 -shuffle=on ./...
go test -v -count=1 -shuffle=on -coverprofile=coverage.out -tags "unit integration" ./...