1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[Golang]メモ

Last updated at Posted at 2022-10-31

とりあえず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",
		})
	})
}

requestを送って返ってきた値を取り出す

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)

}


Map

// キーと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]r.Use()

ミドルウエア追加するときにつかう

デフォルトライブラリだけhttpを返す

main.go
// 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)

set-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))
    })

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?