Snippets Collections
return errors.New(fmt.Sprintf("invalid input, unknown animal '%s', usage: newanimal <name> <%s>", kind, strings.Join(validAnimals, "|")))
package main

import "fmt"

type commonPerson struct {
    A string
    B string
    C string
}

type PersonA struct {
    commonPerson
}

func (p PersonA) String() string {
    return fmt.Sprintf("A: %s, %s, %s", p.A, p.B, p.C)
}

// This function is just here so that PersonA implements personInterface
func (p PersonA) personMarker() {}

type PersonB struct {
    commonPerson
}

func (p PersonB) String() string {
    return fmt.Sprintf("B: %s, %s, %s", p.A, p.B, p.C)
}

// This function is just here so that PersonB implements personInterface
func (p PersonB) personMarker() {}

type personInterface interface {
    personMarker()
}

var smartPerson personInterface

func smartAction(personType string) {
    common := commonPerson{
        A: "foo",
        B: "bar",
        C: "Hello World",
    }

    switch personType {
    case "A":
        smartPerson = PersonA{commonPerson: common}
    case "B":
        smartPerson = PersonB{commonPerson: common}
    }
}

func main() {
    smartAction("A")
    fmt.Println(smartPerson)
    smartAction("B")
    fmt.Println(smartPerson)
}
package main

import (
	"fmt"
)

func bubbleSort(a []int) {
	var temp int
	for j := 0; j < len(a); j++ {
		for i := 0; i < (len(a) - 1); i++ {
			if a[i] > a[i+1] {
				temp = a[i]
				a[i] = a[i+1]
				a[i+1] = temp
			}
		}
	}
	fmt.Println(temp)
}

func inputNums() []int {
	var input int
	var number int

	fmt.Scan(&input)
	s := make([]int, input)

	for i := 0; i < input; i++ {
		fmt.Scan(&number)
		s[i] = number
	}
	return s
}

func outputNums(b []int) {
	for i := 0; i < len(b); i++ {
		fmt.Print(b[i])
		fmt.Print(" ")
	}
}

func main() {
	nums := inputNums()
	bubbleSort(nums)
	outputNums(nums)
}
package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

// Write a program which allows the user to get information about a predefined set of animals; "cow", "bird" and "snake"
// Your program should present the user with a prompt “>”
// Your program accepts one request at a time from the user, prints out the answer to the request, and prints out a new prompt
// Your program should continue in this loop forever
// Every request from the user must be a single line containing 2 strings, the former an animal and the latter an action, e.g "cow" "speak"
// Your program should process each request by printing out the requested data

type Animal struct {
	food       string
	locomotion string
	noise      string
}

func (a Animal) Eat() string {
	return a.food
}

func (a Animal) Move() string {
	return a.locomotion
}

func (a Animal) Speak() string {
	return a.noise
}

func main() {
	cow := Animal{food: "grass", locomotion: "walk", noise: "moo"}
	bird := Animal{food: "seeds", locomotion: "fly", noise: "peep"}
	snake := Animal{food: "mouse", locomotion: "slither", noise: "hsss"}

	animalMap := make(map[string]Animal)
	animalMap["cow"] = cow
	animalMap["bird"] = bird
	animalMap["snake"] = snake

	scanner := bufio.NewScanner(os.Stdin)
	for {
		fmt.Println(">")
		scanner.Scan()
		inpt := strings.Split(scanner.Text(), " ")

		animal := animalMap[inpt[0]]

		switch {
		case inpt[1] == "speak":
			fmt.Println(animal.Speak())
		case inpt[1] == "eat":
			fmt.Println(animal.Eat())
		case inpt[1] == "move":
			fmt.Println(animal.Move())
		}
	}
}
package main

import (
	"fmt"
)

type Animal struct {
	food, locomotion, sound string
}

func (v Animal) Eat() {
	fmt.Println(v.food)
}

func (v Animal) Move() {
	fmt.Println(v.locomotion)
}

func (v Animal) Speak() {
	fmt.Println(v.sound)
}

func main() {
	m := map[string]Animal{
		"cow" : Animal{"grass","walk","moo"},
		"bird" : Animal{"worms","fly","peep"},
		"snake" : Animal{"mice","slither","hsss"},
	}
	for{
		fmt.Print(">")
		name:=""
		action:=""
		fmt.Scan(&name,&action)
		if action=="eat"{
			m[name].Eat()
		} else if action=="move"{
			m[name].Move()
		} else if action=="speak"{
			m[name].Speak()
		}
	}
}
func getFloatValue(text string) float64 {
	var value float64
	fmt.Printf("Enter %s: ", text)
	_, err := fmt.Scan(&value)
	if err != nil {
		fmt.Println(err.Error())
		os.Exit(1)
	}

	return value
}
// AddSignedCookie adds the specified cookie to the response and also adds an
// additional 'signed' cookie that is used to validate the cookies value when
// SignedCookie is called.
func (c *Context) AddSignedCookie(cookie *http.Cookie) (*http.Cookie, error) {

	// make the signed cookie
	signedCookie := new(http.Cookie)

	// copy the cookie settings
	signedCookie.Path = cookie.Path
	signedCookie.Domain = cookie.Domain
	signedCookie.RawExpires = cookie.RawExpires
	signedCookie.Expires = cookie.Expires
	signedCookie.MaxAge = cookie.MaxAge
	signedCookie.Secure = cookie.Secure
	signedCookie.HttpOnly = cookie.HttpOnly
	signedCookie.Raw = cookie.Raw

	// set the signed cookie specifics
	signedCookie.Name = toSignedCookieName(cookie.Name)
	signedCookie.Value = Hash(cookie.Value)

	// add the cookies
	http.SetCookie(c.ResponseWriter, cookie)
	http.SetCookie(c.ResponseWriter, signedCookie)

	// return the new signed cookie (and no error)
	return signedCookie, nil

}
# syntax=docker/dockerfile:1

##
## Build
##
FROM golang:1.16-buster AS build

WORKDIR /app

COPY go.mod ./
COPY go.sum ./
RUN go mod download

COPY *.go ./

RUN go build -o /docker-gs-ping

##
## Deploy
##
FROM gcr.io/distroless/base-debian10

WORKDIR /

COPY --from=build /docker-gs-ping /docker-gs-ping

EXPOSE 8080

USER nonroot:nonroot

ENTRYPOINT ["/docker-gs-ping"]
# syntax=docker/dockerfile:1

# Alpine is chosen for its small footprint
# compared to Ubuntu
FROM golang:1.16-alpine

WORKDIR /app

# Download necessary Go modules
COPY go.mod ./
COPY go.sum ./
RUN go mod download

# ... the rest of the Dockerfile is ...
# ...   omitted from this example   ...
package main

import (
	"net/http"
	"os"

	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
)

func main() {

	e := echo.New()

	e.Use(middleware.Logger())
	e.Use(middleware.Recover())

	e.GET("/", func(c echo.Context) error {
		return c.HTML(http.StatusOK, "Hello, Docker! <3")
	})

	e.GET("/ping", func(c echo.Context) error {
		return c.JSON(http.StatusOK, struct{ Status string }{Status: "OK"})
	})

	httpPort := os.Getenv("HTTP_PORT")
	if httpPort == "" {
		httpPort = "8080"
	}

	e.Logger.Fatal(e.Start(":" + httpPort))
}
package main

import "fmt"

import "rsc.io/quote"

func main() {
    fmt.Println(quote.Go())
}
package main

import "fmt"

func main() {
    fmt.Println("Hello, World!")
}
output "public_ip" {
  value = aws_instance.example.public_ip
  description = "The public IP of the webserver"
}
resource "aws_instance" "example" {
   ami = "ami-0c55b159cbfafe1f0"
   instance_type = "t2.micro"
}
func (r *DeploymentRollbacker) Rollback(obj runtime.Object, updatedAnnotations map[string]string, toRevision int64, dryRunStrategy cmdutil.DryRunStrategy) (string, error) {
	if toRevision < 0 {
		return "", revisionNotFoundErr(toRevision)
	}
	accessor, err := meta.Accessor(obj)
	if err != nil {
		return "", fmt.Errorf("failed to create accessor for kind %v: %s", obj.GetObjectKind(), err.Error())
	}
	name := accessor.GetName()
	namespace := accessor.GetNamespace()

	// TODO: Fix this after kubectl has been removed from core. It is not possible to convert the runtime.Object
	// to the external appsv1 Deployment without round-tripping through an internal version of Deployment. We're
	// currently getting rid of all internal versions of resources. So we specifically request the appsv1 version
	// here. This follows the same pattern as for DaemonSet and StatefulSet.
	deployment, err := r.c.AppsV1().Deployments(namespace).Get(context.TODO(), name, metav1.GetOptions{})
	if err != nil {
		return "", fmt.Errorf("failed to retrieve Deployment %s: %v", name, err)
	}

	rsForRevision, err := deploymentRevision(deployment, r.c, toRevision)
	if err != nil {
		return "", err
	}
	if dryRunStrategy == cmdutil.DryRunClient {
		return printTemplate(&rsForRevision.Spec.Template)
	}
	if deployment.Spec.Paused {
		return "", fmt.Errorf("you cannot rollback a paused deployment; resume it first with 'kubectl rollout resume deployment/%s' and try again", name)
	}

	// Skip if the revision already matches current Deployment
	if equalIgnoreHash(&rsForRevision.Spec.Template, &deployment.Spec.Template) {
		return fmt.Sprintf("%s (current template already matches revision %d)", rollbackSkipped, toRevision), nil
	}

	// remove hash label before patching back into the deployment
	delete(rsForRevision.Spec.Template.Labels, appsv1.DefaultDeploymentUniqueLabelKey)

	// compute deployment annotations
	annotations := map[string]string{}
	for k := range annotationsToSkip {
		if v, ok := deployment.Annotations[k]; ok {
			annotations[k] = v
		}
	}
	for k, v := range rsForRevision.Annotations {
		if !annotationsToSkip[k] {
			annotations[k] = v
		}
	}

	// make patch to restore
	patchType, patch, err := getDeploymentPatch(&rsForRevision.Spec.Template, annotations)
	if err != nil {
		return "", fmt.Errorf("failed restoring revision %d: %v", toRevision, err)
	}

	patchOptions := metav1.PatchOptions{}
	if dryRunStrategy == cmdutil.DryRunServer {
		patchOptions.DryRun = []string{metav1.DryRunAll}
	}
	// Restore revision
	if _, err = r.c.AppsV1().Deployments(namespace).Patch(context.TODO(), name, patchType, patch, patchOptions); err != nil {
		return "", fmt.Errorf("failed restoring revision %d: %v", toRevision, err)
	}
	return rollbackSuccess, nil
}
// equalIgnoreHash returns true if two given podTemplateSpec are equal, ignoring the diff in value of Labels[pod-template-hash]
// We ignore pod-template-hash because:
// 1. The hash result would be different upon podTemplateSpec API changes
//    (e.g. the addition of a new field will cause the hash code to change)
// 2. The deployment template won't have hash labels
func equalIgnoreHash(template1, template2 *corev1.PodTemplateSpec) bool {
	t1Copy := template1.DeepCopy()
	t2Copy := template2.DeepCopy()
	// Remove hash labels from template.Labels before comparing
	delete(t1Copy.Labels, appsv1.DefaultDeploymentUniqueLabelKey)
	delete(t2Copy.Labels, appsv1.DefaultDeploymentUniqueLabelKey)
	return apiequality.Semantic.DeepEqual(t1Copy, t2Copy)
}
// listReplicaSets returns a slice of RSes the given deployment targets.
// Note that this does NOT attempt to reconcile ControllerRef (adopt/orphan),
// because only the controller itself should do that.
// However, it does filter out anything whose ControllerRef doesn't match.
func listReplicaSets(deployment *appsv1.Deployment, getRSList rsListFunc) ([]*appsv1.ReplicaSet, error) {
	// TODO: Right now we list replica sets by their labels. We should list them by selector, i.e. the replica set's selector
	//       should be a superset of the deployment's selector, see https://github.com/kubernetes/kubernetes/issues/19830.
	namespace := deployment.Namespace
	selector, err := metav1.LabelSelectorAsSelector(deployment.Spec.Selector)
	if err != nil {
		return nil, err
	}
	options := metav1.ListOptions{LabelSelector: selector.String()}
	all, err := getRSList(namespace, options)
	if err != nil {
		return nil, err
	}
	// Only include those whose ControllerRef matches the Deployment.
	owned := make([]*appsv1.ReplicaSet, 0, len(all))
	for _, rs := range all {
		if metav1.IsControlledBy(rs, deployment) {
			owned = append(owned, rs)
		}
	}
	return owned, nil
}
package main

import (
	"fmt"
)

func main() {
	fmt.Println("Hello, playground")
}
package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
)

func main() {
	res, err := http.Get("https://raw.githubusercontent.com/asos-craigmorten/opine/0.12.0/examples/hello-world/index.ts")
	if err != nil {
		log.Fatal(err)
	}
	deno, err := ioutil.ReadAll(res.Body)
	res.Body.Close()
		if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%s", deno)

}
"[go]": {

        "editor.formatOnSave": false,
        "editor.codeActionsOnSave": {
            "source.organizeImports": false
        },
    },
    "go.formatTool": "gofmt",
package main

import (
	"fmt"
	"sort"
)

type Grams int

func (g Grams) String() string { return fmt.Sprintf("%dg", int(g)) }

type Organ struct {
	Name   string
	Weight Grams
}

type Organs []*Organ

func (s Organs) Len() int      { return len(s) }
func (s Organs) Swap(i, j int) { s[i], s[j] = s[j], s[i] }

// ByName implements sort.Interface by providing Less and using the Len and
// Swap methods of the embedded Organs value.
type ByName struct{ Organs }

func (s ByName) Less(i, j int) bool { return s.Organs[i].Name < s.Organs[j].Name }

// ByWeight implements sort.Interface by providing Less and using the Len and
// Swap methods of the embedded Organs value.
type ByWeight struct{ Organs }

func (s ByWeight) Less(i, j int) bool { return s.Organs[i].Weight < s.Organs[j].Weight }

func main() {
	s := []*Organ{
		{"brain", 1340},
		{"heart", 290},
		{"liver", 1494},
		{"pancreas", 131},
		{"prostate", 62},
		{"spleen", 162},
	}

	sort.Sort(ByWeight{s})
	fmt.Println("Organs by weight:")
	printOrgans(s)

	sort.Sort(ByName{s})
	fmt.Println("Organs by name:")
	printOrgans(s)

}

func printOrgans(s []*Organ) {
	for _, o := range s {
		fmt.Printf("%-8s (%v)\n", o.Name, o.Weight)
	}
}
  //split by separator and pick the first one. 
  //This has all the characters till null excluding null itself.
  retByteArray := bytes.Split(byteArray[:], []byte{0}) [0]

  // OR 

  //If you want a true C-like string including the null character
  retByteArray := bytes.SplitAfter(byteArray[:], []byte{0}) [0]
star

Wed Nov 16 2022 15:43:52 GMT+0000 (UTC)

#go
star

Tue Nov 15 2022 16:56:47 GMT+0000 (UTC) https://stackoverflow.com/questions/70778524/go-how-to-create-and-initialize-a-struct-instance-based-on-conditions-when-the

#go
star

Tue Nov 15 2022 16:52:04 GMT+0000 (UTC)

#go
star

Tue Nov 15 2022 16:51:18 GMT+0000 (UTC)

#go
star

Tue Nov 15 2022 16:49:46 GMT+0000 (UTC)

#go
star

Sun Nov 13 2022 11:47:32 GMT+0000 (UTC)

#go
star

Thu Jul 07 2022 09:37:51 GMT+0000 (UTC) https://www.google.com/search?q

#shell #go #install
star

Fri Jun 17 2022 17:10:26 GMT+0000 (UTC) https://golang.hotexamples.com/examples/net.http/Cookie/HttpOnly/golang-cookie-httponly-method-examples.html

#go
star

Tue Feb 08 2022 20:28:15 GMT+0000 (UTC) https://docs.docker.com/language/golang/build-images/

#go
star

Tue Feb 08 2022 20:27:58 GMT+0000 (UTC) https://docs.docker.com/language/golang/build-images/

#go
star

Tue Feb 08 2022 20:14:46 GMT+0000 (UTC) https://docs.docker.com/language/golang/build-images/

#go
star

Mon Feb 07 2022 19:16:26 GMT+0000 (UTC) https://go.dev/doc/tutorial/getting-started

#go
star

Mon Feb 07 2022 19:13:16 GMT+0000 (UTC) https://go.dev/doc/tutorial/getting-started

#go
star

Tue Jun 22 2021 17:56:30 GMT+0000 (UTC)

#go
star

Tue Jun 22 2021 17:45:37 GMT+0000 (UTC)

#go
star

Sun Mar 28 2021 07:25:33 GMT+0000 (UTC)

#go #kubernetes #kubectl
star

Sun Mar 28 2021 07:22:28 GMT+0000 (UTC)

#go #kubernetes #kubectl
star

Sat Dec 26 2020 16:21:53 GMT+0000 (UTC) https://play.golang.org/

#go
star

Sat Nov 21 2020 21:55:13 GMT+0000 (UTC) https://golang.org/pkg/net/http/

#go
star

Sat Nov 21 2020 02:28:05 GMT+0000 (UTC) https://stackoverflow.com/questions/48124565/why-does-vscode-delete-golang-source-on-save

#go
star

Fri Oct 30 2020 21:34:30 GMT+0000 (UTC) https://golang.org/pkg/sort/

#go
star

Mon May 11 2020 14:52:46 GMT+0000 (UTC) https://stackoverflow.com/questions/14230145/how-to-convert-a-zero-terminated-byte-array-to-string

#go

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension