Minikube Code Analysis and go language-1

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

[TOC]

Gossip

Recently you need to look at Kubernetes (abbreviated k8s ) and docker related technical information, incidentally learn the go language.

Tried a variety of issues, such as mirroring downloads and network configuration through Minikube deployment.
Although k8s very hot, but the information is very few, and domestic keen on the integration or re-build the wheel, for these Go tools to implement the internal analysis of the discussion is not much.

So take advantage of the recent time, while minikube reading the source side read "The Go programming Language", the minikube structure, the main process and implementation of an analysis, the Go language should also be able to use the knowledge, and accompanied by k8s and docker related knowledge, as well as gossip.

纸上得来终觉浅绝知此事要躬行
Project version
Go v1.8.3
Minikube v0.20.0
Kubectl v1.7.0

Go Language Introduction

Go是一门开源的编程语言,致力于开发简单、可靠和高效的软件。

The go language began in September 2007 with Google's three engineers Robert Griesemer, Rob Pike, Ken thompson,2009, who was formally announced in November.

The Go project includes languages, tools, and standard libraries, as well as the basics concept.

As a newer high-level language, go has a subsequent advantage: it includes garbage collection, package management systems, functional code, semantic scopes, system invocation interfaces, and constant-based UTF-8 strings.

But go has only a relatively small number of features and is unlikely to add more feature support.
For example, go has no implicit number conversions, no constructors or destructors, no operator overloads, no default parameters, no inheritance, no generics, no exceptions, no macros, no function callouts, and no thread-local storage.

The go language itself is mature and stable, and is guaranteed backwards compatibility.

Install the latest go

Https://golang.org/doc/install

# 删除系统已经安装的golangsudo apt remove golang-go# 下载最新版本wget https://storage.googleapis.com/golang/go1.8.3.linux-amd64.tar.gz# 解压到/usr/local/go下sudo tar -C /usr/local -zxvf go1.8.3.linux-amd64.tar.gz# 把go/bin加入到用户PATH环境变量,或是系统范围 /etc/profileecho "PATH=$PATH:/usr/local/go/bin" >> $HOME/.profile

To view the installed Go version:

$ source ~/.profile $ go versiongo version go1.8.3 linux/amd64

0-go Language Design System

graph TDCSP[CSP, Hoare, 1978]-->SqueakSqueak[Squeak, Cardelli & Pike, 1985]-->NewsqueakNewsqueak[Newsqueak, Pike, 1989]-->AlefAlef[Alef, Winterbottom, 1992]-->GoALGOL-60[ALGOL 60, Bakus etal., 1960]-->PascalPascal[Pascal, Wirth, 1970]-->Modula-2Modula-2[Modula-2, Wirth, 1980]-->OberonOberon[Oberon, Wirth & Gutknecht, 1986]-->Oberon-2Oberon-->Object-OberonObject-Oberon[Object Oberon, Mossenbock, Templ & Griesemer, 1990]-->Oberon-2Oberon-2[Oberon-2, Wirth & Mossenbock, 11991]-->GoALGOL-60-->C[C, Ritchie, 1972]C-->Go[Go, Griesemer, Pike & Thompson, 2009]

Reference Material:

    • Classic Papers in Computer science

1-Infrastructure

    • go runYou can run the Go code file directly

    • go buildCompiling code

    • go fmtHelp formatting code

++helloworld.go++ (Print string)

// Go代码按包组织,类似其它语言的模块或库// 当前Go有100多个包,涵盖了输入输出,排序,文本处理等基本任务package main // main包表示这是可执行文件而不是库代码import "fmt" // fmt包负责处理格式化输入输出// 函数声明是func关键字func main() { // { 必须要跟代码在同一行,不能单独一行    fmt.Println("Hello,世界!") // 默认不用写分号,Go会自动加上} // Go默认采用UTF-8编码,兼容多种语言

++echo.go++ (echo command parameter)

package mainimport ( // 导入多个包的常用形式    "fmt"    "os")func main() {    var sep = ""  // Go不允许声明没有用到的变量    // range关键字,数组切分跟Python类似,无需括号    for _, arg := range os.Args[1:] { // := 是声明变量的简写        sep += arg + " " // 支持逆波兰表达式,仅支持i++形式,不支持++i    }    fmt.Println(sep)}

++dup.go++ (count duplicate rows)

package mainimport ( // 导入多个包的常用形式    "bufio"    "fmt"    "os")func main() {    counts := make(map[string]int) // 内置函数make创建一个新的map类型变量    if len(os.Args) > 1 {        for _, file := range os.Args[1:] { // 如果有参数则作为文件打开            f, err := os.Open(file)            if err != nil { // 错误值                fmt.Fprintf(os.Stderr, "dup: %v\n", err)                continue            } else {                countLines(f, counts)                f.Close()            }        }    } else {        countLines(os.Stdin, counts)    }    for line, num := range counts {        if num > 1 { // 不需要`(`,但`{`还是要有            fmt.Printf("> %d\t'%s'\n", num, line) // 与C语言的printf类似        }    }}// 声明函数参数的形式,counts是引用类型func countLines(f *os.File, counts map[string]int) {    for input := bufio.NewScanner(f); input.Scan(); { // for可以替代while        counts[input.Text()]++    }}

++gif.go++ (Generate GIF dynamic graph)

Package main//shows the standard image package import for Go ("image" "Image/color"///The last part of the reference pack, such as color. White "image/gif" "IO" "math" "Math/rand" "OS"//a compact way to declare a composite type, see part fourth var palette = []color. Color{color. White, color.  Black}//slice//declares constants, equivalent to giving some values a const (///constant can only be a number, string, or bool value white = 0//First color in palette black = 1//Next Color in Palette) Func main () {lissajous (OS. Stdout)}func Lissajous (out IO. Writer) {Const (cycles = 5//number of complete x oscillator revolutions res = 0.001//Angul AR resolution size =//Image canvas covers [-size.    +size] Nframes = +//number of animation frames delay = 8//delay between frames in 10ms units ) Freq: = Rand. Float64 () * 3.0//relative frequency of y oscillator anim: = gif. Gif{loopcount:nframes}//struct phase: = 0.0//Phase difference for I: = 0; i < nframes; i++ {rect: = image. Rect (0, 0, 2*size+1, 2*size+1) img: = image. newpaletted (rect, palette) for t: = 0.0; T < Cycles*2*math. Pi; T + = res {x: = Math. Sin (t) y: = Math. Sin (t*freq + Phase) img. Setcolorindex (Size+int (x*size+.5), Size+int (y*size+.5), black)} phase + = 1 Anim. Delay = Append (anim. Delay, delay) anim. Image = Append (anim. Image, IMG)} gif. Encodeall (out, &anim)}

++fetch.go++ (get URL content in parallel)

package main // main包表示这是可执行文件而不是库代码import (    "fmt"    "io"    "io/ioutil"    "net/http"    "os"    "time")func main() { // main函数运行运行于一个goroutine内    start := time.Now()    ch := make(chan string) // channel是在goroutine间消息通信的机制    for _, url := range os.Args[1:] {        go fetch(url, ch) // goroutine是并行执行的函数,go语句建立goroutine    }    for range os.Args[1:] {        fmt.Println(<-ch) // 消息传递是阻塞式的    }    fmt.Printf("%.2fs elapsed\n", time.Since(start).Seconds())}func fetch(url string, ch chan<- string) {    start := time.Now()    resp, err := http.Get(url)    if err != nil {        ch <- fmt.Sprint(err)        return    }    nb, err := io.Copy(ioutil.Discard, resp.Body)    resp.Body.Close()    if err != nil {        ch <- fmt.Sprintf("while reading %s: %v\n", url, err)        return    }    secs := time.Since(start).Seconds()    ch <- fmt.Sprintf("%.2fs, %7d, %s", secs, nb, url)}

++server.go++ (Web server sample)

package mainimport (    "fmt"    "log"    "net/http"    "sync")var mu sync.Mutexvar count intfunc main() {    http.HandleFunc("/", handler)    http.HandleFunc("/counter", counter)    log.Fatal(http.ListenAndServe("localhost:8000", nil))}func handler(w http.ResponseWriter, r *http.Request) {    fmt.Fprintf(w, "%s %s %s\n", r.Method, r.URL, r.Proto)    for k, v := range r.Header {        fmt.Fprintf(w, "Header[%s] = %q\n", k, v)    }    fmt.Fprintf(w, "Host = %q\n", r.Host)    fmt.Fprintf(w, "RemoteAddr = %q\n", r.RemoteAddr)    if err := r.ParseForm(); err != nil {        log.Print(err)    }    for k, v := range r.Form {        fmt.Fprintf(w, "Form[%q] = %q\n", k, v)    }    mu.Lock()    count++    mu.Unlock()    fmt.Fprintf(w, "URL.path = %q\n", r.URL.Path)}func counter(w http.ResponseWriter, r *http.Request) {    mu.Lock()    fmt.Fprintf(w, "Count: %d\n", count)    mu.Unlock()}
    The
    • Switch statement is similar to the C language but has no fall through attribute (with fallthrough statement)

    • named type, A C-like struct

    • Pointer, similar to the C language, supports * and & operator, but does not support pointer operations

    • Method is a function function in a named type Similar to C + + class functions the

    • Interface is an abstract type that declares the same method

    • go doc http.file can view help information for a package

    • Comment Support /* ... */ and // two ways

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.