zl程序教程

您现在的位置是:首页 >  后端

当前栏目

神奇的go语言(开始篇)

Go语言 开始 神奇
2023-09-27 14:27:10 时间


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


    从前接触脚本语言不多,但是自从遇到go之后,就开始慢慢喜欢上了这个脚本语言。go语言是google设计,主要用来从事web、服务器侧程序的开发,学习起点低。一般熟练掌握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 简单web服务器,可以用作webapi接口使用

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