HTTP Handlers

func main() {  
    h := Handler{}  
    mux := http.NewServeMux()  
    mux.HandleFunc("GET /{id}", h.Get)
  
    err := http.ListenAndServe(":8080", mux)  
    if err != nil {  
       panic(err)  
    }  
}
  
func (h Handler) Get(w http.ResponseWriter, r *http.Request) {  
    id := r.PathValue("id")  
  
    data := Body{  
       Name: id,  
    }  
  
    b, err := json.Marshal(data)  
    if err != nil {  
       w.WriteHeader(http.StatusBadRequest)  
       return  
    }  
  
    _, _ = w.Write(b)  
}
  
type Body struct {  
    Name string `json:"name"`  
}  
  
type Handler struct{}  

Json Marshal

data := Body{  
    Name: id,  
}  
 
b, err := json.Marshal(data)

Json Unmarshal

body, err := 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 s1

Sync Package

WaitGroup 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)
}

go 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" ./...