1. 程式人生 > 其它 >關於Go語言在服務端做Restful介面和socket通訊

關於Go語言在服務端做Restful介面和socket通訊

關於REST的定義,我就不扯了~ 大家可以看我以前的博文。

下圖即是REST的架構圖:

當REST架構的約束條件作為一個整體應用時,將生成一個可以擴充套件到大量客戶端的應用程式。它還降低了客戶端和伺服器之間的互動延遲。統一介面簡化了整個系統架構,改進了子系統之間互動的可見性。REST簡化了客戶端和伺服器的實現,而且對於使用REST開發的應用程式更加容易擴充套件。

其實說白了,就是根據不同的方法,來分類不同的任務~

package mainimport (
    "fmt"
    "github.com/drone/routes"
    "net/http")func getuser(w http.ResponseWriter, r *http.Request) {
    params := r.URL.Query()
    uid := params.Get(":uid")
    fmt.Fprintf(w, "you are get user %s", uid)}func modifyuser(w http.ResponseWriter, r *http.Request) {
    params := r.URL.Query()
    uid := params.Get(":uid")
    fmt.Fprintf(w, "you are modify user %s", uid)}func deleteuser(w http.ResponseWriter, r *http.Request) {
    params := r.URL.Query()
    uid := params.Get(":uid")
    fmt.Fprintf(w, "you are delete user %s", uid)}func adduser(w http.ResponseWriter, r *http.Request) {
    params := r.URL.Query()
    uid := params.Get(":uid")
    fmt.Fprint(w, "you are add user %s", uid)
    fmt.Printf("you are add user %s", uid)}//xiaorui.ccfunc main() {
    mux := routes.New()
    mux.Get("/user/:uid", getuser)
    mux.Post("/user/:uid", modifyuser)
    mux.Del("/user/:uid", deleteuser)
    mux.Put("/user/:uid", adduser)
    http.Handle("/", mux)
    http.ListenAndServe(":8088", nil)}//xiaorui.cc

結果:

接著咱們再說下 go的socket 。

客戶端的情況

服務端的情況:

server.go

package mainimport (
    "fmt"
    "net"
    "os")func main() {
    var (
        host   = "127.0.0.1"
        port   = "8080"
        remote = host + ":" + port
        data   = make([]byte, 1024)
    )
    fmt.Println("Initiating server... (Ctrl-C to stop)")
    lis, err := net.Listen("tcp", remote)
    defer lis.Close()
    if err != nil {
        fmt.Println("Error when listen: ", remote)
        os.Exit(-1)
    }
    for {
        var res string
        conn, err := lis.Accept()
        if err != nil {
            fmt.Println("Error accepting client: ", err.Error())
            os.Exit(0)
        }
        go func(con net.Conn) {
            fmt.Println("New connection: ", con.RemoteAddr())
            for {
                length, err := con.Read(data)
                if err != nil {
                    fmt.Printf("Client %v quit.n", con.RemoteAddr())
                    con.Close()
                    return
                }
                res = string(data[0:length])
                fmt.Printf("%s said: %sn", con.RemoteAddr(), res)
                res = "You said:" + res
                con.Write([]byte(res))
            }
        }(conn)
    }}

Client的go程式碼

package mainimport (
    "fmt"
    "net"
    "os")var str stringvar msg = make([]byte, 1024)func main() {
    var (
        host   = "127.0.0.1"
        port   = "8080"
        remote = host + ":" + port    )
    con, err := net.Dial("tcp", remote)
    defer con.Close()
    if err != nil {
        fmt.Println("Server not found.")
        os.Exit(-1)
    }
    fmt.Println("Connection OK.")
    for {
        fmt.Printf("Enter a sentence:")
        fmt.Scanf("%sn", &str)
        if str == "quit" {
            fmt.Println("Communication terminated.")
            os.Exit(1)
        }
        in, err := con.Write([]byte(str))
        if err != nil {
            fmt.Printf("Error when send to server: %dn", in)
            os.Exit(0)
        }
        length, err := con.Read(msg)
        if err != nil {
            fmt.Printf("Error when read from server.n")
            os.Exit(0)
        }
        str = string(msg[0:length])
        fmt.Println(str)
    }}

Go的併發模式

package mainimport (
        "fmt"
        "runtime")func say(s string) {
        for i := 0; i < 5; i++ {
                runtime.Gosched()
                fmt.Println(s)
        }}func main() {
        go say("world")
        say("end")}

這裡就簡單的講講,深入的話,大家自己找官方的資料。