golang實現get和post請求的服務端和客戶端


服務端

在golang中,實現一個普通的http接口可以處理get請求和x-www-form-urlencoded類型的post請求,而如果想實現處理json數據的post請求,則需要用另外的方式實現,接收的參數要從request.Body中讀取:

getpost.go

package main

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

func main()  {

	http.HandleFunc("/login1", login1)
	http.HandleFunc("/login2", login2)
	http.ListenAndServe("0.0.0.0:8080", nil)
}

type Resp struct {
	Code	string `json:"code"`
	Msg		string `json:"msg"`
}

type  Auth struct {
	Username string `json:"username"`
	Pwd 	 string   `json:"password"`
}

//post接口接收json數據
func login1(writer http.ResponseWriter,  request *http.Request)  {
	var auth Auth
	if err := json.NewDecoder(request.Body).Decode(&auth); err != nil {
		request.Body.Close()
		log.Fatal(err)
	}
	var result  Resp
	if auth.Username == "admin" && auth.Pwd == "123456" {
		result.Code = "200"
		result.Msg = "登錄成功"
	} else {
		result.Code = "401"
		result.Msg = "賬戶名或密碼錯誤"
	}
	if err := json.NewEncoder(writer).Encode(result); err != nil {
		log.Fatal(err)
	}
}

//接收x-www-form-urlencoded類型的post請求或者普通get請求
func login2(writer http.ResponseWriter,  request *http.Request)  {
	request.ParseForm()
	username, uError :=  request.Form["username"]
	pwd, pError :=  request.Form["password"]

	var result  Resp
	if !uError || !pError {
		result.Code = "401"
		result.Msg = "登錄失敗"
	} else if username[0] == "admin" && pwd[0] == "123456" {
		result.Code = "200"
		result.Msg = "登錄成功"
	} else {
		result.Code = "203"
		result.Msg = "賬戶名或密碼錯誤"
	}
	if err := json.NewEncoder(writer).Encode(result); err != nil {
		log.Fatal(err)
	}
}

客戶端

golang的標准api中用於http客戶端請求的主要有三個api : http.Get,http.Post,http.PostForm,其區別如下:

API 特點
http.Get 發送get請求
http.Post post請求提交指定類型的數據
http.PostForm post請求提交application/x-www-form-urlencoded數據

在使用http客戶端api的時候要注意一個問題:請求地址的url必須是帶http://協議頭的完整url,不然請求結果為空。

getpostclient.go

package main

import (
	"net/http"
	"fmt"
	"io/ioutil"
	"net/url"
	"encoding/json"
	"bytes"
)

type  auth struct {
	Username string `json:"username"`
	Pwd 	 string   `json:"password"`
}

func main()  {
	get()
	postWithJson()
	postWithUrlencoded()
}

func get()  {
	//get請求
	//http.Get的參數必須是帶http://協議頭的完整url,不然請求結果為空
	resp, _ := http.Get("http://localhost:8080/login2?username=admin&password=123456")
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	//fmt.Println(string(body))
	fmt.Printf("Get request result: %s\n", string(body))
}

func postWithJson()  {
	//post請求提交json數據
	auths := auth{"admin","123456"}
	ba, _ := json.Marshal(auths)
	resp, _ := http.Post("http://localhost:8080/login1","application/json", bytes.NewBuffer([]byte(ba)))
	body, _ := ioutil.ReadAll(resp.Body)
	fmt.Printf("Post request with json result: %s\n", string(body))
}

func postWithUrlencoded()  {
	//post請求提交application/x-www-form-urlencoded數據
	form := make(url.Values)
	form.Set("username","admin")
	form.Add("password","123456")
	resp, _ := http.PostForm("http://localhost:8080/login2", form)
	body, _ := ioutil.ReadAll(resp.Body)
	fmt.Printf("Post request with application/x-www-form-urlencoded result: %s\n", string(body))
}

運行getpost.go后再運行getpostclient輸出結果如下:

Get request result: {"code":"200","msg":"登錄成功"}

Post request with json result: {"code":"200","msg":"登錄成功"}

Post request with application/x-www-form-urlencoded result: {"code":"200","msg":"登錄成功"}

Process finished with exit code 0


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM