C# 與 Go 的互通代碼筆記

互通基礎篇:C# 結合 Golang 開發

1. Go 項目結構推薦

【參考資料】Go 項目結構推薦
在一開始搭建 Go 項目時,就使用推薦的目錄結構方式,可以讓項目結構更清晰,互通性增強,從而也增強項目的可閱讀性。

/cmd
項目主要應用文件(/cmd/myapps),保持文件與項目生成可執行文件名稱相同,通常是較簡單的main.go文件調用/internal和/pkg代碼
/internal
項目內部調用文件,包含應用私有代碼(/internal/app/myapps),應用通過代碼(/internal/pkg/myprivlibs)
Standard Go Project Layout

2. GO 加解密相關

【參考資料】Des、Rsa加解密互通系列之Golang 實現
【參考資料】Go 實現 DES 加密和解密一些知識要點

3. POST 參數生成

參考資料】golang使用http client發起get和post請求示例

3.1 拼接 application/x-www-form-urlencoded 的 post 字符串

可以使用以下方式:

var r http.Request
r.ParseForm()
r.Form.Add("uuid", "aaaaaaaa&lasf=aaa")
bodystr := strings.TrimSpace(r.Form.Encode())

3.2 關鍵寫法

resp, err := http.Post("http://www.01happy.com/demo/accept.php",
        "application/x-www-form-urlencoded",
        strings.NewReader(bodystr))

req, err := http.NewRequest("POST", "http://www.01happy.com/demo/accept.php", strings.NewReader(bodystr))

3.3 具體方法

//發送GET請求
//url:請求地址
//response:請求返回的內容
func Get(url string) (response string) {
    client := http.Client{Timeout: 5 * time.Second}
    resp, error := client.Get(url)
    defer resp.Body.Close()
    if error != nil {
        panic(error)
    }

    var buffer [512]byte
    result := bytes.NewBuffer(nil)
    for {
        n, err := resp.Body.Read(buffer[0:])
        result.Write(buffer[0:n])
        if err != nil && err == io.EOF {
            break
        } else if err != nil {
            panic(err)
        }
    }

    response = result.String()
    return
}

//發送POST請求
//url:請求地址,data:POST請求提交的數據,contentType:請求體格式,如:application/json
//content:請求放回的內容
func Post(url string, data interface{}, contentType string) (content string) {
    jsonStr, _ := json.Marshal(data)
    reader := bytes.NewBuffer(jsonStr)
    switch data.(type) {
    case string:
        reader = bytes.NewBufferString(data.(string))
        fmt.Println(data.(string))
    }

    req, err := http.NewRequest("POST", url, reader)
    req.Header.Add("content-type", contentType)
    if err != nil {
        panic(err)
    }
    defer req.Body.Close()

    client := &http.Client{Timeout: 5 * time.Second}
    resp, error := client.Do(req)
    if error != nil {
        panic(error)
    }
    defer resp.Body.Close()

    result, _ := ioutil.ReadAll(resp.Body)
    content = string(result)
    return
}

4. 一些小知識點

map 作 json 功能

func BaseResultJson(errCode int, errMsg string) map[string]interface{} {
    m := make(map[string]interface{})
    m["err_code"] = errCode
    m["err_msg"] = errMsg
    return m
}

m := common.BaseResultJson(101, "請求失敗!")
j, _ := json.Marshal(m)
fmt.Println(string(j))

Go DLL 中的異常得自己處理,否則會導致程序崩潰(閃退)。

func TrialDefer() (content string) {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println(r)
            m := common.BaseResultJson(101, "請求失敗!")
            j, _ := json.Marshal(m)
            content = string(j)
        }
    }()

    var r http.Request
    r.ParseForm()
    timeStr := time.Now().Format("20060102")

    r.Form.Add("timeStr", timeStr)
    bodystr := strings.TrimSpace(r.Form.Encode())

    content = Post("http://www.sag.xcom/xxx", bodystr, "application/x-www-form-urlencoded")

    return
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章