返回首页 神奇的 Go 语言

Go 语言简介

从前接触脚本语言不多,但是自从遇到 Go 之后,就开始慢慢喜欢上了这个脚本语言。Go 语言是 Google 设计,主要用来从事 Web 服务器侧程序的开发,学习起点低。一般熟练掌握 C、Python 的朋友花上几个小时就可以学会Go 语言。

安装环境

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

centos: sudo yum install golang
ubuntu: sudo apt-get install golang

学习资源

本来学习 Go 语言,最好的学习环境应该是官方网站。所以,建议大家可以访问一下 coolshell.cn网站,上面有 Go 语言的内容,分别是个 Go 语言(上)、Go 语言(下)。

编译方法

如果需要生成执行文件,输入 go build name.go, 其中 name.go 表示你需要编译的那个文件名,这时会有一个执行文件生成。

如果你需要立即看到效果,输入 go run name.go 即可。

范例

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 简单 Web 服务器

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)  

} 

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

e.3 带有表单处理的 Web 服务器

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] 
<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,你会有不同的惊喜。

上一篇: 关于 下一篇: 基本语法