[Golang]笔记

暂时已经准备好了进行API测试所需的样本。

开发一个Get的API

func SampleGetAPI(router *gin.RouterGroup) {
	router.GET("/ping", func(c *gin.Context) {
		// queryparamerの値を取得する
		fmt.Println(c.Query("samplequery"))
		c.JSON(200, gin.H{
			"Message": "pong",
		})
	})
}

发送请求并提取返回的值

func TestRes(t *testing.T) {

	resp, _ := http.Get("http://localhost:8080/ping")
	defer resp.Body.Close()
	body, _ := io.ReadAll(resp.Body)
	//これが中身
	var post responseBody
	if err := json.Unmarshal(body, &post); err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("%+v\n", post.Message)
}

创建用于Post的API

func SamplePostPage(router *gin.RouterGroup) {
	router.POST("/samplepost", func(c *gin.Context) {

		bodyAsByteArray, _ := io.ReadAll(c.Request.Body)
		jsonBody := string(bodyAsByteArray)
		fmt.Println(jsonBody)
		var post responseBody
		if err := json.Unmarshal(bodyAsByteArray, &post); err != nil {
			fmt.Println(err)
			fmt.Println("ggg")
			return
		}
		fmt.Printf("%+v\n", post.Sample)
		fmt.Println("kkk")
		c.JSON(200, gin.H{
			"Message": "pong",
		})
	})
}

func TestResPost(t *testing.T) {
	values := map[string]string{"Sample": "aaaabbbb"}

	jsonValue, _ := json.Marshal(values)
	resp, err := http.Post(
		"http://localhost:8080/samplepost",
		"application/json",
		bytes.NewBuffer(jsonValue),
	)
	defer resp.Body.Close()
	resp.Header.Add("Content-Type", "application/json")
	if err != nil {
		fmt.Println(err)
		return
	}

	println(resp)

}


地图

// キーとvalueがType指定なしで100個文の要素のメモリ領域を確保
target := make(map[interface{}]interface{}, 100)
target["k1"] = 1
target[3] = "hello"
target["world"] = 1.05
fmt.Println(target)

map[3:hello k1:1 world:1.05]

使用gin的中间件功能

在添加中间件时使用

只返回默认库中的http

// html
    http.HandleFunc("/healthcheck", func(w http.ResponseWriter, r *http.Request) {
        
        fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
    })

    http.ListenAndServe(":8000", nil)

设置Cookie

func runserver(){
    
    http.HandleFunc("/healthcheck", func(w http.ResponseWriter, r *http.Request) {
     
        cookie := http.Cookie{
            Name: "csrftoken",
            Value:"abcd",
        }
        
        http.SetCookie(w, &cookie)
        fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
    })

广告
将在 10 秒后关闭
bannerAds