c语言编程笔录

首页 >   > 笔记大全

笔记大全

Go语言中的实时通信和RESTful架构

更新时间:2023-10-03

段落一:Go语言中实时通信的基础知识

Go语言对实时通信有较好的支持,因为它本身是一种高并发的编程语言,同时也很容易使用goroutine和channel等机制来处理并发,这使得编写实时通信的应用变得非常简单。

下面是一个使用websocket协议进行实时通信的示例代码:

package main

import (
    "log"
    "net/http"

    "github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{
    ReadBufferSize:  1024,
    WriteBufferSize: 1024,
}

func handleWebSocket(w http.ResponseWriter, r *http.Request) {
    conn, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        log.Println(err)
        return
    }
    defer conn.Close()

    for {
        _, message, err := conn.ReadMessage()
        if err != nil {
            log.Println(err)
            break
        }
        log.Printf("收到消息:%s\n", message)
        err = conn.WriteMessage(websocket.TextMessage, message)
        if err != nil {
            log.Println(err)
            break
        }
    }
}

func main() {
    http.HandleFunc("/ws", handleWebSocket)
    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        log.Fatal(err)
    }
}

段落二:RESTful架构的基础知识

RESTful架构是一种以资源为中心的架构风格,它强调对资源的操作,倡导使用URL来代表资源,使用HTTP协议的请求方式来对资源进行增删改查,这使得RESTful架构在Web应用开发中非常流行。

下面是一个使用Go语言编写的RESTful风格的Web应用示例:

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "net/http"

    "github.com/gorilla/mux"
)

type User struct {
    ID       int    `json:"id,omitempty"`
    Username string `json:"username,omitempty"`
    Password string `json:"password,omitempty"`
}

var users []User

func getUsersEndpoint(w http.ResponseWriter, req *http.Request) {
    json.NewEncoder(w).Encode(users)
}

func getUserEndpoint(w http.ResponseWriter, req *http.Request) {
    params := mux.Vars(req)
    for _, user := range users {
        if strconv.Itoa(user.ID) == params["id"] {
            json.NewEncoder(w).Encode(user)
            return
        }
    }
    json.NewEncoder(w).Encode(&User{})
}

func createUserEndpoint(w http.ResponseWriter, req *http.Request) {
    var user User
    _ = json.NewDecoder(req.Body).Decode(&user)
    users = append(users, user)
    json.NewEncoder(w).Encode(users)
}

func main() {
    router := mux.NewRouter()

    users = append(users, User{ID: 1, Username: "admin", Password: "admin"})
    users = append(users, User{ID: 2, Username: "user1", Password: "user1"})

    router.HandleFunc("/users", getUsersEndpoint).Methods("GET")
    router.HandleFunc("/users/{id}", getUserEndpoint).Methods("GET")
    router.HandleFunc("/users", createUserEndpoint).Methods("POST")

    fmt.Println("服务启动...")
    log.Fatal(http.ListenAndServe(":8080", router))
}

段落三:Go语言中使用WebSocket实现聊天室

下面是一个使用WebSocket协议和Go语言实现简单聊天室的示例:

package main

import (
    "log"
    "net/http"
    "sync"

    "github.com/gorilla/websocket"
)

type Client struct {
    conn *websocket.Conn
    mtx  sync.Mutex
}

var clients []*Client

func handleWebSocket(w http.ResponseWriter, r *http.Request) {
    upgrader := websocket.Upgrader{}
    conn, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        log.Println(err)
        return
    }
    defer conn.Close()

    client := &Client{conn: conn}
    clients = append(clients, client)

    for {
        _, message, err := conn.ReadMessage()
        if err != nil {
            log.Println(err)
            break
        }
        log.Printf("收到消息:%s\n", message)
        for _, c := range clients {
            if c != client {
                c.mtx.Lock()
                err = c.conn.WriteMessage(websocket.TextMessage, message)
                c.mtx.Unlock()
                if err != nil {
                    log.Println(err)
                }
            }
        }
    }

    var newClients []*Client
    for _, c := range clients {
        if c != client {
            newClients = append(newClients, c)
        }
    }
    clients = newClients
}

func main() {
    http.HandleFunc("/ws", handleWebSocket)
    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        log.Fatal(err)
    }
}

段落四:Go语言中使用RESTful架构实现用户管理

下面是一个使用RESTful架构和Go语言实现简单用户管理的示例:

package main

import (
    "encoding/json"
    "log"
    "net/http"
    "strconv"

    "github.com/gorilla/mux"
)

type User struct {
    ID       int    `json:"id,omitempty"`
    Username string `json:"username,omitempty"`
    Password string `json:"password,omitempty"`
}

var users []User

func getUsersEndpoint(w http.ResponseWriter, req *http.Request) {
    json.NewEncoder(w).Encode(users)
}

func getUserEndpoint(w http.ResponseWriter, req *http.Request) {
    params := mux.Vars(req)
    for _, user := range users {
        if strconv.Itoa(user.ID) == params["id"] {
            json.NewEncoder(w).Encode(user)
            return
        }
    }
    json.NewEncoder(w).Encode(&User{})
}

func createUserEndpoint(w http.ResponseWriter, req *http.Request) {
    var user User
    _ = json.NewDecoder(req.Body).Decode(&user)
    users = append(users, user)
    json.NewEncoder(w).Encode(users)
}

func updateUserEndpoint(w http.ResponseWriter, req *http.Request) {
    params := mux.Vars(req)
    for i, user := range users {
        if strconv.Itoa(user.ID) == params["id"] {
            users[i].Username = user.Username
            users[i].Password = user.Password
            json.NewEncoder(w).Encode(users)
            return
        }
    }
    json.NewEncoder(w).Encode(users)
}

func deleteUserEndpoint(w http.ResponseWriter, req *http.Request) {
    params := mux.Vars(req)
    var newUsers []User
    for _, user := range users {
        if strconv.Itoa(user.ID) != params["id"] {
            newUsers = append(newUsers, user)
        }
    }
    users = newUsers
    json.NewEncoder(w).Encode(users)
}

func main() {
    router := mux.NewRouter()

    users = append(users, User{ID: 1, Username: "admin", Password: "admin"})
    users = append(users, User{ID: 2, Username: "user1", Password: "user1"})

    router.HandleFunc("/users", getUsersEndpoint).Methods("GET")
    router.HandleFunc("/users/{id}", getUserEndpoint).Methods("GET")
    router.HandleFunc("/users", createUserEndpoint).Methods("POST")
    router.HandleFunc("/users/{id}", updateUserEndpoint).Methods("PUT")
    router.HandleFunc("/users/{id}", deleteUserEndpoint).Methods("DELETE")

    log.Fatal(http.ListenAndServe(":8080", router))
}