Snippets Collections
/* Go is statically typed. A type defines the set of values and the set of operations that can take place on those valies. */

// Elementary or primitive types: int, float, bool, string.

// Structured or composite types: struct, array, slice, map, channel.

// Interfaces describe the behavior of a type.

/* We can create a user defined data type. It's also possible to have an alias for data types. An alias for int for example could be declared like so: */

type IZ int

// Then, to declar an integer variable, we have to use an alias like so:

var a IZ = 5

// To define more tha one type we can do it like so:

type (
	IZ int
	FZ float32
  	STR string
)

/* We can convert a value into another type of value through type-casting. However, Go does not allow implicit conversion, which means that Go never does such a conversion by itself. The conversion must be done explicitly as valueOfTypeB = typeB(valuePFTypeA). For example: */

package main
import "fmt"

func main(){
    var number float32 = 5.2         // Declared a floating point variable
    fmt.Println(number)              // Printing the value of variable
    fmt.Println(int(number))         // Printing the type-casted result
/* Clean, readable code and simplicity are major goals of Go development. Therefore, the names of things in Go should be short, concise, and evocative. Long names with mixed caps and underscores which are often seen e.g., in Java or Python code, sometimes hinder readability. Names should not contain an indication of the package. A method or function which returns an object is named as a noun, no Get… is needed. To change an object, use SetName. If necessary, Go uses MixedCaps or mixedCaps rather than underscores to write multiword names. */

// Filenames are in lower case and separated by an underscore if necessary

lower_case.go

/* Go keywords: break, default, func, interface, select, case, defer, go, map, struct, chan, else, goto, package, switch, const, fallthrough, if, range, type, continue, for, import, return, var */

/* Identifuers are case-sensitive, begin with a letter or an underscore, and are followed by 0 or more letter or Unicode digits. For example: X56, group1, _x23, i, etc.

Blank identifiers (_) can be used in declarations or variable assignments, but their value is discarded, so it can't be used in the code that follows. 

Delimiters used in Go: parentheses (), Braces {} and Brackets [].

Punctuation characters in GO:
- .
- ,
- ;
- :
- ...
*/

/* Go programs consist of keywords, constants, variables, operators, types and functions. 

The code is structured in statements. Statements don't need to end with a ;. The Go compiler automatically inserts semicolons at the end of statements. 

However, if multiple statements are written on one line (not encouraged), they must be separated by a semicolon.
wget https://dl.google.com/go/go1.21.0.linux-amd64.tar.gz
sudo tar -xvf go1.21.0.linux-amd64.tar.gz
sudo mv go /usr/local
sudo ln -s /usr/local/go/bin/* /usr/bin
rm go1.21.0.linux-amd64.tar.gz
export GOPATH=$HOME/go
export PATH=$PATH:/usr/local/go/bin:$GOPATH/bin
package main

import (
	"fmt"
	"time"
)

func main() {
	date := time.Now()

	if date.Day() == 13 && date.Month().String() == "September" {
		fmt.Println("Happy Programmers Day!")
	}
}
wget https://dl.google.com/go/go1.21.0.linux-amd64.tar.gz
sudo tar -xvf go1.21.0.linux-amd64.tar.gz
sudo mv go /usr/local
sudo ln -s /usr/local/go/bin/* /usr/bin
rm go1.21.0.linux-amd64.tar.gz
export GOPATH=$HOME/go
export PATH=$PATH:/usr/local/go/bin:$GOPATH/bin
package main

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

func main() {
    url := "https://api.currencyapi.com/v3/latest"
    method := "GET"

    client := &http.Client {
}
req, err := http.NewRequest(method, url, nil)

if err != nil {
    fmt.Println(err)
    return
}
req.Header.Add("apikey", "YOUR-API-KEY")

res, err := client.Do(req)
if err != nil {
    fmt.Println(err)
    return
}
defer res.Body.Close()

body, err := ioutil.ReadAll(res.Body)
if err != nil {
    fmt.Println(err)
    return
}
fmt.Println(string(body))
}
func handlePayload(c *gin.Context) {
    var payload interface{}

    if err := c.ShouldBindJSON(&payload); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    // Melakukan pengecekan tipe data secara dinamis
    switch p := payload.(type) {
    case map[string]interface{}:
        // Tipe data berupa map[string]interface{}
        // Lakukan sesuatu dengan payload berupa map
        fmt.Println("Received payload as map:", p)
    case []interface{}:
        // Tipe data berupa []interface{}
        // Lakukan sesuatu dengan payload berupa slice
        fmt.Println("Received payload as slice:", p)
    default:
        // Tipe data lainnya
        // Lakukan sesuatu dengan payload sesuai kebutuhan
        fmt.Println("Received payload with unknown type")
    }

    c.JSON(http.StatusOK, gin.H{"message": "Payload received successfully"})
}
package main

import "fmt"

func main() {
    var num int
    fmt.Scan(&num)
    fmt.Println(getFirstNumber(num))
}

func getFirstNumber(num int) int {
     if num < 10 {
        return num
     } else {
         return getFirstNumber(num / 10)
    }
}
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

Sun Jun 30 2024 21:48:59 GMT+0000 (Coordinated Universal Time)

#go
star

Fri Jun 14 2024 22:20:20 GMT+0000 (Coordinated Universal Time)

#go
star

Tue Nov 21 2023 00:35:20 GMT+0000 (Coordinated Universal Time)

#go
star

Wed Sep 13 2023 19:20:03 GMT+0000 (Coordinated Universal Time)

#go
star

Sat Sep 02 2023 12:08:22 GMT+0000 (Coordinated Universal Time)

#ubuntu #linux #go #golang
star

Thu Aug 17 2023 15:42:53 GMT+0000 (Coordinated Universal Time) https://www.codinguru.online/compiler/go

#go #golang #compiler #codinguru
star

Tue Aug 08 2023 08:07:35 GMT+0000 (Coordinated Universal Time) https://currencyapi.com/docs/examples/go-currency-converter

#go #currencyconverter #exchangerates #currency #api
star

Tue Jul 18 2023 03:07:09 GMT+0000 (Coordinated Universal Time)

#go
star

Tue Jul 04 2023 09:09:45 GMT+0000 (Coordinated Universal Time) https://www.thiscodeworks.com/extension/initializing?newuser

#go
star

Sun Jan 22 2023 19:39:41 GMT+0000 (Coordinated Universal Time)

#go
star

Wed Nov 16 2022 15:43:52 GMT+0000 (Coordinated Universal Time)

#go
star

Tue Nov 15 2022 16:56:47 GMT+0000 (Coordinated Universal Time) 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 (Coordinated Universal Time)

#go
star

Tue Nov 15 2022 16:51:18 GMT+0000 (Coordinated Universal Time)

#go
star

Tue Nov 15 2022 16:49:46 GMT+0000 (Coordinated Universal Time)

#go
star

Sun Nov 13 2022 11:47:32 GMT+0000 (Coordinated Universal Time)

#go
star

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

#shell #go #install
star

Fri Jun 17 2022 17:10:26 GMT+0000 (Coordinated Universal Time) 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 (Coordinated Universal Time) https://docs.docker.com/language/golang/build-images/

#go
star

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

#go
star

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

#go
star

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

#go
star

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

#go
star

Tue Jun 22 2021 17:56:30 GMT+0000 (Coordinated Universal Time)

#go
star

Tue Jun 22 2021 17:45:37 GMT+0000 (Coordinated Universal Time)

#go
star

Sun Mar 28 2021 07:25:33 GMT+0000 (Coordinated Universal Time)

#go #kubernetes #kubectl
star

Sun Mar 28 2021 07:22:28 GMT+0000 (Coordinated Universal Time)

#go #kubernetes #kubectl
star

Sun Mar 28 2021 04:58:15 GMT+0000 (Coordinated Universal Time)

#go #kubernetes #kubectl
star

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

#go
star

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

#go
star

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

#go
star

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

#go
star

Mon May 11 2020 14:52:46 GMT+0000 (Coordinated Universal Time) 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