Posts

Showing posts with the label golang

Golang - For loop

Three-component loop sum := 0 for i := 1; i < 5; i++ { sum += i } fmt.Println(sum) // 10 (1+2+3+4) This version of the Go for loop works just as in C/Java/JavaScript. The init statement,  i := 0 , runs. The condition,  i < 5 , is evaluated. If it’s true, the loop body executes, otherwise the loop terminates. The post statement,  i++ , executes. Back to step 2. The scope of  i  is limited to the loop. While loop If the init and post statements are omitted, the Go  for  loop behaves like a C/Java/JavaScript while loop: power := 1 for power < 5 { power *= 2 } fmt.Println(power) // 8 (1*2*2*2) The condition,  i < 5 , is evaluated. If it’s true, the loop body executes, otherwise the loop terminates. Back to step 1. Infinite loop By also leaving out the condition, you get an infinite loop. sum := 0 for { sum++ // repeated forever } fmt.Println(sum) // unreachable For each loop Looping ov...

Golang - Writing data to file

package main import ( "bufio" "fmt" "os" ) func main() { fileHandle, _ := os.Create("output.txt") writer := bufio.NewWriter(fileHandle) defer fileHandle.Close() fmt.Fprintln(writer, "String I want to write") writer.Flush() }

Golang - Read a file line by line

import ( "bufio" "os" ) func FileToLines ( filePath string ) ( lines [] string , err error ) { f , err := os . Open ( filePath ) if err != nil { return } defer f . Close () scanner := bufio . NewScanner ( f ) for scanner . Scan () { lines = append ( lines , scanner . Text ()) } err = scanner . Err () return }

Building webserver with golang

Image
How to build a simple webserver with Go Code: package main import ( "fmt" "net/http" ) func main () {     http. HandleFunc ("/", func (w http.ResponseWriter, r *http.Request) { fmt. Fprintf (w, " Golang webserver. ")     })     http. HandleFunc ("/hello", func(w http.ResponseWriter, r *http.Request) { fmt. Fprintf (w, " Hello World! ")     })     fs := http. FileServer (http.Dir("static/"))     http. Handle ("/static/", http. StripPrefix ("/static/", fs))     http. ListenAndServe (":3000", nil) }