您的位置:首页 > 编程语言 > Go语言

奇妙的go语言(開始篇)

2017-05-21 16:48 316 查看


【 声明:版权全部。欢迎转载,请勿用于商业用途。  联系信箱:feixiaoxing @163.com】


    从前接触脚本语言不多,可是自从遇到go之后,就開始慢慢喜欢上了这个脚本语言。go语言是google设计,主要用来从事web、server側程序的开发,学习起点低。

一般熟练掌握C、python的朋友花上几个小时就能够学会go语言。


a) 安装环境


    鉴于个人主要使用linux进行工作,所以这里介绍的都是linux下的安装方式。

    centos: sudo yum install golang

    ubuntu: sudo apt-get install golang


b) 学习资源


    本来学习go语言,最好的学习环境应该是官方站点,可是因为GFW的原因,訪问上还是有一定的困难。所以,建议大家能够訪问一下coolshell.cn站点,上面有go语言的内容,各自是个go语言(上)go语言(下)


c) 书籍


    不管是亚马逊、当当还是京东上面,关于go语言的书籍不是非常多。可是有两本我认为还是不错的,一本是谢孟军的《go web编程》,另外一本是许式伟的《go 语言编程》。


d) 编译方法


    假设须要生成运行文件,输入go build name.go, 当中name.go表示你须要编译的那个文件名称,这时会有一个运行文件生成。

    假设你须要马上看到效果。输入go run name.go就可以。


e)范例

    e.1 add.go

package main

import "fmt"

func add(a int, b int)(c int) {

c =  a + b
return c
}

func main() {

c := add(1 ,2)
fmt.Println(c)

}

    直接输入go run add.go就能够打印效果了。



    e.2 简单webserver

package main

import (
"fmt"
"net/http"
)

func sayHelloName(w http.ResponseWriter, r *http.Request) {

fmt.Fprintf(w, "hello, world")
}

func main() {

http.HandleFunc("/", sayHelloName)
http.ListenAndServe(":9090", nil)

}

    这时一个简单的webserver,首先go run hello.go之后。打开os下的一个browser,输入http://127.0.0.1:9090,你就会在网页上看到web的打印了。 


    e.3 带有表单处理的webserver

package main

import (

"fmt"
"html/template"
"net/http"
)

func sayHelloName(w http.ResponseWriter, r* http.Request) {

fmt.Fprintf(w, "hello, world")
}

func login(w http.ResponseWriter, r* http.Request) {

if r.Method == "GET" {

t, _ := template.ParseFiles("login.gtpl");
t.Execute(w, nil)
} else {

r.ParseForm()
fmt.Println("username:", r.Form["username"])
fmt.Println("password", r.Form["password"])

}

}

func main() {

http.HandleFunc("/", sayHelloName)
http.HandleFunc("/login", login)
http.ListenAndServe(":9090", nil)
}

    上面给出的仅仅是代码内容,你还须要一个login.gtpl模板文件,


<html>
<head>
<title> </title>
</head>

<body>
<form action="http://127.0.0.1:9090/login" method="post">
user: <input type="text" name ="username">
pass: <input type="password" name="password">
<input type="submit" value="login">
</form>
</body>
</html>

    运行go代码之后。试着在浏览器下输入127.0.0.1:9090和127.0.0.1:9090/login,你会有不同的惊喜。    




内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: