如何将元素从切片1复制和删除到切片2

时间:2019-12-26 06:10:17

标签: go reverse-proxy

我正在研究一个反向代理,该代理可以接收来自客户端的所有请求,将其放入一个片中,然后使用 TCP协议将它们逐个发送到服务器强>。当请求转发到服务器时,应在切片中将其删除。当服务器回复时,反向代理将响应放入另一个分片中,然后相应地将其转发给客户端。

转发的响应或请求会立即从切片中删除,以为即将到来的请求或响应腾出空间。

图片,以便更好地理解: enter image description here

代码:

   package main

    import (
        "fmt"
        "os"
        "bufio"
    )


    //* function for deleting 
    //*****************************
func RemoveIndex(s []string, index int) []string {
    return append(s[:index], s[index+1:]...)
}

func main() {

type clientreq struct {
    clientId string
    request string
    reqindex int
}


    //* User information
    //*****************************

    reader := bufio.NewReader(os.Stdin)
    fmt.Print("Enter client1 info: ")
    text, _ := reader.ReadString('\n')
    fmt.Print("Enter client2 info: ")
    text1, _ := reader.ReadString('\n')
    fmt.Println("the client 1 request is about =", text)
    fmt.Println("the client 2 request is about =", text1)       

    //* append, delete and copy
    //*****************************

    all := []string{}
    fmt.Println("empty slice1 is created ", all) 
    all = append(all, text, text1)
    fmt.Println("the info was added into slice1", all)

    slice2 := make([]string, len(all), (cap(all))*2) // make a second slice bigger than the 1st
    copy(slice2, all) // copy all the elements into the slice 2

    fmt.Println("copied in slice2 ", slice2) 
    removeIndex := RemoveIndex(all, 0)
    fmt.Println("the first index in slice 1 was deleted ", removeIndex) 
    fmt.Println("the slice 2 still has all the copied items ", slice2) 
    //removeIndex[0] = string(7)
    // fmt.Println("add a value ", all) 
    //fmt.Println("add new value: ", removeIndex) 
}

0 个答案:

没有答案