o language variables, functions, SOCKS5 proxy servers

Source: Internet
Author: User
Tags sprintf

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

1
2
3
4
5
6
7
8
9
10
11
12
= Use must use the first VAR declaration for example:
var a
A = 100

Or
var b = 100

Or
var c int = 100

: = is declared and assigned, and the system automatically infers the type without the need for the VAR keyword
D: = 100

Go has a special variable underscore "_" to indicate that any value assigned to it will be discarded

_, ret:= 2, 3//2 assignment discarded

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 [www.yigozongdai2.cn 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

1
2
3
4
Const (
constName1 [Type] = Val1
constName2 [Type] = Val2
)

Example 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 an executable file
Package Main

Import "FMT"//Importing Package

var id = 123456

/*
ID2: = 654321
External to the function: =, errors occur at compile time, local variable declarations should be inside the function
Non-declaration statement outside function body
*/

Const PI = 3.14//Constant declaration

Each program that can be run independently contains the entry function main, which is the same as other languages, but without parameters and return values
Func Main () {
var num int
num = 100
Fmt. PRINTLN (num)//Output 100

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 = 10
)
Fmt. Println (A, B)//Output 9 10
Fmt. PRINTLN (ID)//output 123456
Fmt. PRINTLN (PI)//Output 3.14

/*
PI = 3.1415
Change the value of the constant, the compilation will appear error
Cannot assign to PI
Cannot use 3.1415 (type float64) as type ideal in assignment
*/
}

2. Function usage

1) Go language function format

1
2
3
4
5
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

1
<span style= "color: #0000FF;" >vim chuangshi88.cn/.go</span>
1
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
100
Hello 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 www.078881.cn/.")
}

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", www.hjd1956.com/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 0
Printing in G 1
Printing in G 2
Printing in G 3
panicking!
Defer in G 3
Defer in G 2
Defer in G 1
Defer in G 0
Recovered in F 4
Returned 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, 1024)
N, Err: = C.conn.read (b)
If err! = Nil && Err! = Io. EOF {Panic (err)}

BUF: = bytes. Newbuffer (B[0:n])

Err = binary. Read (buf, www.lgzxyl.com 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, 128)

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 *proxy) proxyconn (conn net.www.t1yl9.cn/conn) {
c: = &proxycoder{conn}

M: = C.readmethods ()
Fmt. Println (M)

C.returnmethod ()

C.serve ()
}

Func handleconnection (Conn net. Conn) {
BUF: = Make ([]byte, 1024)

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", ": 1080")
If err! = Nil {
Fmt. Printf ("Bind error\n")
Return
}
for {
Conn, err: = ln. Accept ()
If err! = Nil {
Fmt. Printf ("Accept www.hjd157.com error\n")
Continue
}
Go Defaultproxy.proxyconn (conn)
Go handleconnection (conn)
}
}

o language variables, functions, SOCKS5 proxy servers

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.