Golang interface

Проверка, что наша структура user реализует интерфейс User
Создаем переменную которая не нужна с типом User и значением структуры user



var _ User = &user{}

type User interface {
	ChangFIO(newFio string)
}

type user struct {
	FIO string
}

func (u *user) ChangFIO(newFio string) {

}


Invoke golang



package main

import (
	"fmt"
	"reflect"
)

var funcMap = map[string]interface{}{
	"Hello": Hello,
}

func Hello(name string) {
	fmt.Printf("Hello, %s!\n", name)
}

func main() {
	nameFunc := "Hello"

	if fn, ok := funcMap[nameFunc]; ok {
		funcValue := reflect.ValueOf(fn)
		args := []reflect.Value{reflect.ValueOf("Gopher")}
		funcValue.Call(args)
	} else {
		fmt.Println("Function not found!")
	}
}


gracefully shutdown HTTP server

	// listen to OS signals and gracefully shutdown HTTP server
	stopped := make(chan struct{})
	go func() {
		sigint := make(chan os.Signal, 1)
		signal.Notify(sigint, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
		<-sigint
		ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
		defer cancel()
		if err := srv.Shutdown(ctx); err != nil {
			log.Printf("HTTP Server Shutdown Error: %v", err)
		}
		close(stopped)
	}()

	log.Printf("Starting HTTP server on %s", cfg.HTTPAddr)

	// start HTTP server
	if err := srv.ListenAndServe(); err != http.ErrServerClosed {
		log.Fatalf("HTTP server ListenAndServe Error: %v", err)
	}

	<-stopped

How to Use go:embed in Go

package main

import (
    "embed"
    "html/template"
    "log"
    "net/http"
)

var (
    //go:embed resources
    res embed.FS

    pages = map[string]string{
        "/": "resources/index.gohtml",
    }
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        page, ok := pages[r.URL.Path]
        if !ok {
            w.WriteHeader(http.StatusNotFound)
            return
        }
        tpl, err := template.ParseFS(res, page)
        if err != nil {
            log.Printf("page %s not found in pages cache...", r.RequestURI)
            w.WriteHeader(http.StatusInternalServerError)
            return
        }

        w.Header().Set("Content-Type", "text/html")
        w.WriteHeader(http.StatusOK)
        data := map[string]interface{}{
            "userAgent": r.UserAgent(),
        }
        if err := tpl.Execute(w, data); err != nil {
            return
        }
    })

    http.FileServer(http.FS(res))

    log.Println("server started...")
    err := http.ListenAndServe(":8088", nil)
    if err != nil {
        panic(err)
    }
}
index.gohtml
<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <title>go:embed demo</title>
</head>
<body>
<div>
    <h1>Hello, {{ .userAgent }}!</h1>
    <p>If you see this, then go:embed worked!</p>
</div>
</body>
</html>
GET http://localhost:8088/

 

How to cross-compile Go programs for Windows, macOS, and Linux

You can use the go env command to view the values of these variables on your machine:

$ go env
...
GOARCH="amd64"
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
...

Compile for Windows

Here’s the command you need to run to compile your Go project for a 64-bit Windows machine:

$ GOOS=windows GOARCH=amd64 go build -o bin/app-amd64.exe app.go

In this scenario, GOOS is windows, and GOARCH is amd64 indicating a 64-bit architecture. If you need to support a 32-bit architecture, all you need to do is change GOARCH to 386.

$ GOOS=windows GOARCH=386 go build -o bin/app-386.exe app.go

Compile for macOS

The GOARCH values for Windows are also valid for macOS, but in this case the required GOOS value is darwin:

# 64-bit
$ GOOS=darwin GOARCH=amd64 go build -o bin/app-amd64-darwin app.go

# 32-bit
$ GOOS=darwin GOARCH=386 go build -o bin/app-386-darwin app.go

Compile for Linux

To build your Go program for Linux, use linux as the value of GOOS and the appropriate GOARCH value for your target CPU architecture:

# 64-bit
$ GOOS=linux GOARCH=amd64 go build -o bin/app-amd64-linux app.go

# 32-bit
$ GOOS=linux GOARCH=386 go build -o bin/app-386-linux app.go