This article is to make a detailed record of the explanation and use of Go, and record the problems encountered in learning.

## 2, Environment configuration Go download address: https://golang.org/dl/

Go in the plug-in configuration IDEA: http://jingyan.baidu.com/article/f25ef25446109c482c1b821d.html

Environment configuration for Go:

export GOROOT=/usr/local/go
export GOPATH=$HOME/goworkspace
export PATH=$PATH:$GOROOT/bin:$GOPATH/bin
Copy the code

The first directory for Go the second is the working directory for Go and the third is a direct copy

GOPATH env = GOPATH env = GOPATH env = GOPATH env By convention, three directories need to be created under GOPATH: Bin to store the compiled executable file PKG to store the compiled the generated package source file SRC storage project I have GOPATH at/Users/Demon/Desktop/gowork vi ~ /. Following


## 3. Variable definition

Const age int = 5 // const age int = 5 // const age int = 5 // const age int = 5 // const age int = 5 // const age int = 5 //main() { const ( a = iota // a = 0 b = iota // b = 1 c = iota // c = 2 d = iota // d = 3 ) fmt.Print(a) fmt.Print(b) Print(c) Print(d)} var array [10]int; Array [0] = array := [10]int{1,2,3} var slice []int; // slice = []int{1,2,3} slice := []byte {'a'.'b'.'c'.'d'} / / second / / get the values in the array sun: = [8] int,2,3,4,5,6,7,8 {1} a: = sun [then] / / specified in the index value was obtained from the array, a = 3, // make(Map [string]int) numbers := make(Map [string]int) numbers["1"] = 1 // assign numbers["2"] = 2 // assign numbers["3"] = 3
fmt.Println("The third number is:", numbers["1"Image := map[string]int{"one": 1,"two":2} // map has two return values, the second return value, if there is no key, then ok isfalse, if ok istrue
result,ok := image["two"]
if ok{
	fmt.Print("There",result,"Ah")}else {
	fmt.Print("Doesn't exist.")
}
delete(image,"two"// make(map[string]string) m[make(map[string]string) m["Hello"] = "Bonjour"
m1 := m
m1["Hello"] = "Salut"/ / m [now"hello"] is already SalutCopy the code





Func main() {FMT.Print(“hehe”,add(2,3))}

func add(x int ,y int) int { return x + y }

</br> Function variables can also be defined like this:Copy the code

func add(x ,y int) int { return x + y }

The </br> function can return multiple arguments,Copy the code

func main() { c,d:=back(“1″,”2”); fmt.Print(c,d) }

func back(a ,b string) (string,string) { return a,b }

The return value of the </br> function can also set the variable name and be assigned within the functionCopy the code

func main() { fmt.Print(sum(3)) }

func sum(num int) (x,y int) { x = num * 4 / 9 y = num * 4 return }

</br> // Cut from the number of positions in the string according to the specified numberCopy the code

str := “hellow”; S := STR [2:] FMT.Print(s) // result: llow

The string enclosed in </br> 'is the Raw string, that is, the string is printed in the code as it is printed, without character escape, and the newline is printed as it is. For example, in this example:Copy the code

m := hello world fmt.Print(m)

// Result: Hello world

</br> Tag jump (tag name is case sensitive.)Copy the code

I := 0 Here: // The first word of this line, ending with a colon as the label println(I) I ++ goto Here // Jumps to Here and starts execution again from Here, generating a loop

</br> traverses the collection by key valuesCopy the code

For k,v:=range j {fmt.println (“map’s key:”,k) fmt.println (“map’s val:”,v)}

</br>
Switch
Copy the code

// Switch adds a break by default. If you want to continue, add the fallthrough keyword. Switch can determine many types

i := 1 switch i { case 1: fmt.Print(1) fallthrough case 2: fmt.Print(2) fallthrough }

< / br > pointerCopy the code

X1 := add1(&x) // Call add1(&x) to pass the address of x

Func add1(a *int) int {*a = a+1 return *a // return new value}

Defer is always called before the result of the functionCopy the code

// The function specified after defer will call func ReadWrite() bool {file.open (“file”) defer file.close () if failureX {return false} if failureY { return false } return true }

Methods the referenceCopy the code

// Create a method body of the format func(int) that represents methods of the format, such as add() and delete() type addOrDelete func(int) string

FMT.Print(getContent(2, add))}

func add(a int) string { return strconv.Itoa(a+1) }

func delete(b int) string { return strconv.Itoa(b+1) }

Func getContent(a int, method addOrDelete) string {return method(a)}

Struct objectCopy the code

type user struct { Name string json:name Age int json:age }

Func main() {var user01 user user01.age = 12 user01.name = “DSF” // user02 := user{name:” jun “, If Max (user02, user03) {FMT.Print(” the first one is bigger than the second one “)}}

func max(a, b user) bool { return a.age > b.age }

< / br > anonymous classCopy the code

type student struct { studentName string studentage int }

Type user struct {student //student} type user struct {student //student}

Func main() {// If the object is passed in when the user is declared, all its parameters need to be filled, Myuser := user{student{studentName:”studentName”, studentage:12}, “name”, 21} fmt.Print(myuser.studentName) fmt.Print(myuser.studentage, “\n”) fmt.Print(myuser.name) fmt.Print(myuser.age, “\n”) }

</br> Struct method definitionCopy the code

type student struct { studentName string studentage int }

type user struct { name string age int }

func (stu student)getName() string { return stu.studentName }

func (use user)getName() string { return use.name }

</br>

## 5. Build Web server</br> > Note: r.parseform () must be added, otherwise Post or Get will not Get the data HTTP package to establish the Web serverCopy the code
Func sayhelloName(w http.responsewriter, r * http.request) {r.parseform (); FMT.Println("path", r.ul.path) FMT.Println("scheme", r.URL.Scheme) fmt.Println(r.Form["url_long"]) for k, v := range r.Form { fmt.Println("key:", k) fmt.Println("val:", strings.Join(v, "")) } fmt.Fprintf(w, "Hello astaxie!" } func main() {http.handlefunc ("/", sayhelloName) // Set the access route err := http.listenAndServe (":9090", Nil) // Set the listening port if err! = nil { log.Fatal("ListenAndServe: ", err) } }Copy the code
</br> Login example! [](http://upload-images.jianshu.io/upload_images/2650372-ae38064bdf230415.png? imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)Copy the code

func login(w http.ResponseWriter, R *http.Request) {method := r.thod if method == “GET” {// load the specified page to display, display only t.xecute (w, nil), err is to fetch this file if there is an error, Error t, err := template.parseFiles (“login.html”) log.println (t.execute (w, Nil))} else {r.parseForm () // Parse Post or Get data, FMT.Fprint(w,”username:”, r.store [“username”]) FMT.Fprint(w,”password:”, r.store [“password”])}}

Func main() {// Specify the login interface to request the current directory http.handlefunc (“/login”, login) err := HTTP.ListenAndServe(“:8080”, nil) if err! = nil { log.Fatal(“ListenAndServe: “, err) } }

//Html






## 6. Json parsing and conversion

# # # # transformation

1 Object conversion Json

Var s User b,e := json.Marshal(s) //User converts the json stringife ! = nil{ fmt.Print("There is an error")
	return} FMT.Println(string(b)) // output {"Name":"Larry"."Age":"23"}

Copy the code

2 Convert Json to objects

Result,err := ioutil.ReadAll(r.body) // Read the RequestBody uploaded by the client returns byte[],erriferr ! = nil { fmt.Fprint(w,"Error")}else{var s User json.Unmarshal(result, &s) // convert the json string to User FMT.Print(s.name) // output}Copy the code


arr, _ := js.Get("test").Get("array").Array()
Copy the code



</br>



## database operation< / br > database tutorial: https://github.com/astaxie/build-web-application-with-golang/blob/master/zh/05.2.md MySQL driver download the sampleCopy the code

// Download the corresponding driver go get github.com/graphql-go/graphql

Copy the code

// Install the corresponding driver go install github.com/graphql-go/graphql

Copy the code

// Import driver, if still red, please restart IDE import (_ “github.com/go-sql-driver/mysql” // this is MySql driver “database/ SQL “)


MySql
Copy the code

/ / connect the MySql database db, _ : = SQL. Open (” MySql “, “root: a root @ / jun_data”)

Result,_ := db.Exec(“insert into user values(null,? ,?) “,”junwen”,”21″) // Execute Insert statement, parameter 1 is SQL, parameter 2 is the corresponding value fmt.print (result.lastinsertid ())

Result,_ := db.Exec(“delete from user where _id=?”) FMT.Print(result.rowsaffected ()) // Print the number of affected rows

Result,_ := db.Exec(“update user set username=? where _id=?” FMT.Print(result.rowsaffected ())

Query, _ :=db. query (“select * from USER “) // Execute query statement

for query.Next(){ var id int var name string var age string query.Scan(&id,&name,&age) fmt.Println(“id:”,id) fmt.Println(“name:”,name) fmt.Println(“age:”,age) }

</br>
## 9 Cookie and Session
</br>
Cookie
Copy the code

// SetCookie cook := http.Cookie{Name:”mycook”,Value:”junwen”,Expires: time.now ().add (60)} http.setcookie (w,&cook)

Cookie,_:= r.cookie (“mycook”) ftt.print (cookie.value)

</br>
## file manipulation
</br>
Copy the code

Func main() {os.mkdir (“astaxie”, 0777) // Create a 0777 folder os.mkdirall (“astaxie/test1/test2”, 0777) Remove(“astaxie”) // Delete the folder if err! = nil {fmt.println (err)} os.removeAll (“astaxie”) // Delete all folders, including subfolders

If err is empty, fileInfo exists,err := os.stat (“junwen.txt”)

// Open file and write file, 1 file name and 2 mode: OpenFile(“junwen123.txt”, os.o_append,0666) file.WriteString(“waerwaeraser”) // WriteString}


String handling
</br>
Copy the code

// Check if strings exist.Contains(“seafood”, “foo”)

/ / processing stirng [] type, additional string s: = [] string {” foo “, “bar”, “baz}” FMT. Println (strings. Join (s, “, “)) / / output: foo and bar, baz

Println(strings. index (“chicken”, “Ken “))


## 9 system functions
</br>
Copy the code

Strconv.atoi (a) //String to int, return the result of conversion bool and result int strconv.itoa (a) // int to String, Printf(“v is of type %T\n”,v) // The type of v that can be printed is Printf(F)

## 10. Precautions</br> </br> </br> </br> </br> </br> 1Copy the code

Var a,b int = 1,2

A,b := 1,2 //

</br> 2. When declaring a method or variable, the difference between the private modifier and the public modifier is whether you use case. If you want to Debug a project, you will not be able to Debug the first time, you need to create a go file to Debug, is this a Bug? 4. If the object is converted to A Json string, the first letter of the field in the object must be uppercase, otherwise there is no way to convert, and finally use string(Json) conversion output 5. If you want to reference a method or attribute from a class in another package, you need to import it, but find that the object in the other package cannot be typed? Only classes created in this class are recognized? Solution: You need to set your project's full path to the environment variable GoPath, so that you can identify methods and properties under other packages, etc.## 11. Learning Materials
</br>

https://github.com/astaxie/build-web-application-with-golang/blob/master/zh/preface.md

https://github.com/graphql-go/graphql

http://git.oschina.net/Lemon19950301/APIJSON

https://my.oschina.net/u/943306/blog/151293

https://my.oschina.net/liudiwu/blog/305014?p={{currentPage-1}}

## 12. Conclusion</br> The following two pieces of code, HTTP.ListenAndServe(": 8080"Nil: 8080 is the number of the house. The second parameter is the commander. All the combatants need to attack through the commander, but the commander is too tired alone. The HTTP.HandleFunc section is used to register the implementation of different action tasks. The first parameter is the task and the second parameter is the action. You can pass in your own method, or you can pass in anonymously, as followsCopy the code

http.HandleFunc(“/sng”, func(w http.ResponseWriter,r *http.Request) { fmt.Fprint(w,”sng”) }) http.ListenAndServe(“:8080”,nil)

If he does not register the corresponding service for the corresponding page, he will not respond. ! [](https://upload-images.jianshu.io/upload_images/2650372-995208295888e296.png? imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)Copy the code