Go language variables, functions, SOCKS5 proxy servers

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

The Declaration of variables in the go language is very much like JavaScript, and with the Var keyword, there are several forms of declaration and definition of variables.

1. Variables and Constants

Declaration and initialization of a variable

var m int = 10

Declaring initialization of multiple variables

var I, j, k = 1, 2, 3

Declaration of multiple variables (note the use of parentheses)

var
no int
Name string
)

The declaration does not indicate a type, which is deduced by initializing the value of the

var B = true//bool type

: = implicitly declares variables and assigns values

str: = "mimvp.com"//equivalent to var str string = "mimvp.com"

What is the difference between the Go language = and: =?

= is an assignment,: = is a declaration variable and assigns a value

// = 使用必须使用先var声明例如:var aa = 100  // 或var b = 100  // 或var c int = 100  // := 是声明并赋值,并且系统自动推断类型,不需要var关键字d := 100 // Go中有一个特殊的变量下划线"_" 表示任何赋给它的值将被丢弃_, Ret:= 2, 3     

Go language compiler, the declaration is not used in the error, so the variable declaration must be used, if you want to use a variable must first declare

The go language, like the C language, also uses semicolons to terminate statements in the go language. But unlike the C language, the lexical parser for the go language automatically inserts semicolons in the process of scanning the source code, so you do not need to add semicolons when writing the source code most of the time.

The Go Language Lexical analyzer inserts a semicolon rule: if the last token in front of a new line is an identifier (including words like int and float64), a basic value such as text, or one of the following tags, a semicolon is automatically inserted

The go language usually separates initializers, additions, and increments by using semicolons only in the for statement. Another situation is when you write multiple statements in a row, you also need to use semicolons to separate

Because the Go language lexical analyzer adds a semicolon-specific feature, there are some situations where you need to be aware of:

You should not place the left brace of a control structure (if, for, switch, or select) on the next line.

If you do this, a semicolon will be inserted in front of the curly braces, which may result in unwanted results.

Constants: Values that cannot be changed in a program are generally defined as numeric values, Boolean values, strings, etc.

Format: const constname [Type] = Val

1). var num = 3//Actually 3 is also called a constant

2). An expression in which Val can be an expression but cannot be used for runtime to know the result

3). Pre-defined constants: True/false/iota

4). When defining multiple constants, you can also use the following method

const (      constName1 [type] = val1      constName2 [type] = val2  )

Sample code:

/*** mimvp.com* 2017.1.20*///declares the package name to which the current file belongs, and main is a standalone package that is compiled to generate the executable package main import "FMT"//import packages var id = 12 3456/* Id2: = 654321//Outside the function: =, error at compile time, local variable declaration should be inside function//non-declaration statement outside function body */CO      NST PI = 3.14//constant declaration//each self-running program contains the entry function main, same as other languages, but no parameter and return value Func main () {var num int num = 100 Fmt. PRINTLN (num)//output var num1, num2 int num1, num2 = 1, 2 fmt. Println (NUM1, num2)//Output 1 2 var no1, NO2 = 3, 4 fmt. Println (No1, NO2)//Output 3 4 n1, N2: = 5, 6 fmt. Println (n1, N2)//Output 5 6 _, N: = 7, 8 FMT.     PRINTLN (n)//output 8 var (key1 string Key2 string) key1, Key2 = "K1", "K2" Fmt. Println (Key1, Key2)//Output K1 k2 var (a = 9 B = ten) fmt. Println (A, B)//Output 9 FMT. PRINTLN (ID)//output 123456 FMT.     PRINTLN (PI)//Output 3.14/* PI = 3.1415//Change the value of the constant, compile error//cannot assign to PI//cannot use 3.1415 (type float64) as type ideal in Assignment */}

2. Function usage

1) Go language function format

func GetMsg(i int) (str string) {    fmt.Println(i)    str = "hello mimvp.com"    return str}

Explanatory notes:

Func indicates that this is a function

Getmsg is the name of the function

The (i int) function receives an int parameter, which is an incoming parameter

The (str string) function returns a string that returns a value that is the return parameter

2) Go language function can return multiple values

function returns multiple values, unlike Java, PHP, C and other mainstream languages, but is the same as Python, Lua and other scripting languages

func GetMsg(i int) (str string, err string) {    fmt.Println(i)    str = "hello mimvp.com"    err = "no err"    return str, err} func main() {    fmt.Println(GetMsg(100))}

Compile execution:

$ go build mimvp_func.go $ ./mimvp_func          100hello mimvp.com no err

3) Use of defer

Defer means "call on function exit", especially when reading and writing to a file, you need to call the close operation after open and use the close operation defer

func ReadFile(filePath string)(){    file.Open(filePath)    defer file.Close()          if true {        file.Read()    } else {        return false    }}

The above code meaning is in file. Close is not immediately called after open, and file is called when return is false. Close (), which effectively avoids the memory leak problem in C language.

4) Understanding Panic,recover

It tells a lot of variables and functions, and doesn't describe the use of throw-try-catch.

In the go language, panic and recover are the throw and catch in other languages

Example code:

package main  import "fmt"  func main() {    f()    fmt.Println("Returned normally from f.")}  func f() {    defer func() {        if r := recover(); r != nil {            fmt.Println("Recovered in f", r)        }    }()    fmt.Println("Calling g.")    g(0)    fmt.Println("Returned normally from g.")}  func g(i int) {    if i > 3 {        fmt.Println("Panicking!")        panic(fmt.Sprintf("%v", i))    }    defer fmt.Println("Defer in g", i)    fmt.Println("Printing in g", i)    g(i + 1)}

Operation Result:

$ ./mimvp-try-catch           Calling g.Printing in g 0Printing in g 1Printing in g 2Printing in g 3Panicking!Defer in g 3Defer in g 2Defer in g 1Defer in g 0Recovered in f 4Returned normally from f.

Panic throws the message and jumps out of the function. The recover receives the information and continues processing.

This example understands the basics of mastering recover and panic.

3. SOCKS5 Proxy Server

Package main import ("Net" "FMT" "io" "bytes" "encoding/binary") type Methods struct{ver, nmethods    Uint8 methods Uint8} type Sock5cmd struct{ver, cmd, RSV, Atyp uint8 DST [255]uint8} type Proxycoder struct { Conn Net. Conn} func (c *proxycoder) readmethods () Methods {var m Methods b: = make ([]byte, 1024x768) n, err: = C.conn.read (b) If err! = Nil && Err! = Io. EOF {Panic (err)} buf: = bytes. Newbuffer (b[0:n]) err = binary. Read (buf, Binary. Littleendian, &m.ver) if err! = Nil {fmt. Println ("Binary. Read failed: ", err)} err = binary. Read (buf, Binary. Littleendian, &m.nmethods) if err! = Nil {fmt. Println ("Binary. Read failed: ", err)} err = binary. Read (buf, Binary. Bigendian, &m.methods) if err! = Nil {fmt. Println ("Binary.     Read failed: ", err)} return M} func (c *proxycoder) Returnmethod () {buf: = make ([]byte, 2) buf[0] = 5 BUF[1] = 0 c.conn.write (BUF) fmt.  Println (BUF)} func (c *proxycoder) serve () {buf: = make ([]byte, +) n, err: = C.conn.read (BUF) if err! = Nil && Err! = Io. EOF {Panic (err)} FMT. Println (Buf[:n]) var s string var t string var i int if (buf[3] = = 3) {//domail for i = 4; I < n -2; i++ {s + = FMT. Sprintf ("%c", Buf[i])}} else {//IP4 or ip6 s + = FMT. Sprintf ("%d", buf[4]) for i = 5; i < n-2; i++ {s + = FMT. Sprintf (".%d", Buf[i])}} P: = Make ([]byte, 2) var port uint16 p[1] = buf[n-1] p[0] = buf[n-2 ] B: = bytes. Newbuffer (p) Err = binary. Read (b, Binary. Bigendian, &port) if err! = Nil {fmt. Println ("Binary. Read failed: ", err)} s + = Fmt. Sprintf (":%d", port) switch buf[1] {case 1://tcp t = ' TCP ' case 2://bind case 3:// UDP t = "UDP"} conn, err: = Net. Dial (t, s) if err! = Nil {FMT.    Printf ("%s Connect error%s\n", T, s) buf[1] = 4 c.conn.write (buf[:n]) c.conn.close () return } Buf[1] = 0 c.conn.write (buf[:n]) fmt. Printf ("%s Connect success%s\n", T, s) go serv (conn, c.conn) go serv (c.conn, conn)} func serv (in net. Conn, out net. Conn) {b: = make ([]byte, 10240) for;; {N, err: = in. Read (b) if (Err! = nil) {FMT. Printf ("close\n") in. Close () out. Close () return} FMT. Printf ("Serv%d\n", N) out.    Write (B[:n]); }} type Proxy struct {} func newproxy () *proxy {return &proxy{}} var defaultproxy = Newproxy () func (P *prox Y) proxyconn (conn net. Conn) {c: = &proxycoder{conn} m: = C.readmethods () fmt. Println (M) C.returnmethod () C.serve ()} func handleconnection (conn net. Conn) {buf: = make ([]byte, 1024x768) n, err: = Conn. Read (BUF) if err! = Nil && Err! = Io. EOF {Panic (err)} FMT. Println (Buf[:n])//answer buf[0] = 5 Buf[1] = 0 Conn. Write (Buf[:2]) fmt. Println (Buf[:2])//serve N, err = conn. Read (BUF) if err! = Nil && Err! = Io. EOF {Panic (err)} FMT. Println (BUF[:N]) Conn. Close ()} func main () {ln, err: = Net. Listen ("TCP", ":") if err! = Nil {fmt. Printf ("Bind error\n") return} for {conn, err: = ln. Accept () if err! = Nil {fmt. Printf ("Accept error\n") Continue} Go defaultproxy.proxyconn (conn)//go Handleconnection ( conn)}}
Related Article

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.