Techumber
Home Blog Work

Golang Beginner

Published on January 10, 2019

Example

package main
import "fmt"

func main() {
  fmt.Println("hello, world")
}

Variables & Constants


const PI = 3.141592653589793

// dynamic variables
str:="Hello"
str := `
  Multiline
  string
`
// declare variable
var msg string
var num int
var num flot64
var num float32
var num complex128
var b1 byte
var b uint;

// Type conversion
i := 2
f := float64(i)
u := uint(i)

Structs


type Direction struct {
  TOP string
  BOTTOM string
  LEFT string
  RIGHT string
}

Array & Slice

  // Array
  numbers := [...]int{1, 2, 3, 4, 5}

  // Slices
	var Cities = []string{"New York"}
  // append
  Cities = append(Cities, "Chicago")

  // Remove or pop
  Cities = Cities[:len(a)-1]   // Truncate slice.

  // length
  var noOfCities=len(Cities)

  // slice
  var slice = Cities[1:2]

Pointers

func main () {
  b := *getPointer()
  fmt.Println("Value is", b)
}

func getPointer () (myPointer *int) {
  val := 1
  return &val
}

```go

### Conditions

```go
if City == "NeyWork" || City == "Chicago" {
  doSomething();
}
switch city {
  case "NewYork":

  fallthrough

  default:
    fmt.Println("No City")
}
var Cities = []string{"New York", "Chicago"}

// for-range
for i, val := range entry {
  fmt.Printf("%s", i, val)
}
// for
for count := 0; count <= 10; count++ {
	fmt.Println("My counter is at", count)
}

Function

// lambda functions
myfunc := func() string {
  return "hello"
}

// multi return function
a, b := getMessage()
func getMessage() (a string, b string) {
  return "Hello", "World"
}

packages

import "fmt"
import "math/rand"
// or
import (
  "fmt"
  "math/rand"
)
// or Aliases
import r "math/rand"

Simple http Server


package main

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

func homePage(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Welcome to the HomePage!")
	fmt.Println("Endpoint Hit: homePage")
}

func handleRequests(port string) {
	http.HandleFunc("/", homePage)
	fmt.Println("Running Sever at //localhost:" + port)
	log.Fatal(http.ListenAndServe(":"+port, nil))
}

func main() {
	port := "8081"
	handleRequests(port)
}