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

下图是关于rest的使用介绍,有些老生常谈了。

当REST架构的约束条件作为一个整体应用时,将生成一个可以扩展到大量客户端的应用程序。它还降低了客户端和服务器之间的交互延迟。统一界面简化了整个系统架构,改进了子系统之间交互的可见性。REST简化了客户端和服务器的实现,而且对于使用REST开发的应用程序更加容易扩展。

其实说白了,就是根据不同的方法,来分类不同的任务~


165521917.png

我这边使用golang的drone/routes库实现restful服务。  下面是实现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)
}
//xiaorui.cc

下面说下golang 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: %s\n", con.RemoteAddr(), res)
                res = "You said:" + res
                con.Write([]byte(res))
            }
        }(conn)
    }
}

socket 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("%s\n", &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: %d\n", 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)
    }
}


大家觉得文章对你有些作用! 如果想赏钱,可以用微信扫描下面的二维码,感谢!
另外再次标注博客原地址  xiaorui.cc

发表评论

邮箱地址不会被公开。 必填项已用*标注