51工具盒子

依楼听风雨
笑看云卷云舒,淡观潮起潮落

关于Go语言在服务端做Restful接口和socket通信

REST的架构图:

当REST架构的约束条件作为一个整体应用时,将生成一个可以扩展到大量客户端的应用程序。

它还降低了客户端和服务器之间的交互延迟。统一界面简化了整个系统架构,改进了子系统之间交互的可见性。

REST简化了客户端和服务器的实现,而且对于使用REST开发的应用程序更加容易扩展。

package main

import (
    "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)
}

func 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)
}

go的socket

server.go

package main
import (
    "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 main
import (
    "fmt"
    "net"
    "os"
)
var str string
var 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 main
import (
        "fmt"
        "runtime"
)
func say(s string) {
        for i := 0; i < 5; i++ {
                runtime.Gosched()
                fmt.Println(s)
        }
}
func main() {
        go say("world")
        say("end")
}

标签: 应用程序,服务器,服务端,客户端,接口

赞(2)
未经允许不得转载:工具盒子 » 关于Go语言在服务端做Restful接口和socket通信