Skip to content

Instantly share code, notes, and snippets.

@mtilson
mtilson / main.go
Last active December 31, 2019 02:52
how to create middleware with net/http Handle() by implementing own Handler interface [golang]
package main
import (
"log"
"net/http"
)
type myHandler http.HandlerFunc
func (f myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
@mtilson
mtilson / main.go
Last active December 31, 2019 02:58
how to create middleware with net/http HandleFunc() [golang]
package main
import (
"log"
"net/http"
)
func main() {
http.HandleFunc("/abc", abcMiddleware(doABC))
http.HandleFunc("/abc/by-pass-abc-middleware", doABC)
@mtilson
mtilson / Makefile
Last active March 26, 2024 02:57
how to include build information in the executable [golang] [makefile]
.PHONY: init
init: .git
.git:
@echo ">>> Git initialization: Start"
@git init
@git remote add origin git@github.com:mtilson/gist-example.git
@git add .
@git commit -m "init"
@git tag v0.1.0
@mtilson
mtilson / main.go
Last active June 5, 2023 18:31
how to use context for graceful shutdown [golang]
package main
import (
"context"
"log"
"net"
"os"
"os/signal"
"time"
)
@mtilson
mtilson / main.go
Last active December 24, 2019 20:03
how to use pointers to share elements between slices and maps [golang]
package main
import "fmt"
// Post is the simplest blog post object with ID, count of references, and page slug
type Post struct {
ID string
RefCount int
Slug string
}
@mtilson
mtilson / main.go
Last active January 14, 2020 13:47
how to generate random data [golang] [20lines]
package main
import (
"crypto/rand"
"encoding/hex"
"fmt"
)
func main() {
src := make([]byte, 4)
@mtilson
mtilson / main.go
Last active December 31, 2019 01:36
how to use context, channels, and goroutines to create and gracefully shutdown multiple http server (listener) instances [golang]
package main
import (
"context"
"fmt"
"log"
"net"
"net/http"
"os"
"os/signal"
@mtilson
mtilson / Dockerfile
Last active December 11, 2020 08:33
how to create CI/CD pipeline on localhost with 'make' and 'docker' [golang] [makefile] [dockerfile]
# MI (modules image) is for getting dependencies.
# MI will be cached till the dependency changing.
# It is useful trick to speed up the process of building
FROM golang:1.13 as MI
ADD go.mod go.sum /m/
RUN cd /m && go mod download
# BI (build image) is for building App
FROM golang:1.13 as BI
@mtilson
mtilson / .env
Last active May 9, 2024 09:45
how to rebuild your web app container on every commit with local 'docker-compose' and 'post-commit' git hook [docker] [docker-compose] [git]
APPNAME=myapp
APPVERSION=latest
@mtilson
mtilson / main.go
Last active January 14, 2020 13:48
how to create pure http server - in less than 20 code lines [golang] [20lines]
package main
import (
"net/http"
)
const (
jsonString = `{"hello": "world", "with_love": "from_go"}`
)