0
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 3 years have passed since last update.

json.Unmarshal()でやらかした話

Posted at

はじめに

techtrainの課題をやっている途中postの実装で詰まったことがあったので備忘録を残しときます.

結論

データをcurlで渡すときはデータ形式がJSONであるかちゃんと確認してからやろう

失敗

curl --location --request POST 'http://localhost:8080/user/create' \
--header 'Content-Type: application/json' \
--data-raw 'hoge'

値が取れてない

2020/04/19 09:27:52 invalid character 'h' looking for beginning of value
2020/04/19 09:27:52 0
2020/04/19 09:27:52

成功

curl --location --request POST 'http://localhost:8080/user/create' \
--header 'Content-Type: application/json' \
--data-raw '{
    "name": "hoge"
}'

ちゃんと取れてる

2020/04/19 09:33:03 0
2020/04/19 09:33:03 hoge

コード

package main

import (
	"encoding/json"
	"io/ioutil"
	"log"
	"net/http"

	_ "github.com/go-sql-driver/mysql"
	"github.com/gorilla/mux"
)

type UserCreateRequest struct {
	Id   int    `json:"id"`
	Name string `json:"name"`
}

func userCreateRequest(w http.ResponseWriter, r *http.Request) {
	reqBody, _ := ioutil.ReadAll(r.Body) // []uint8 byte stream
	userCreReq := &UserCreateRequest{}
	err := json.Unmarshal(reqBody, &userCreReq)
	if err != nil {
		log.Printf(err.Error())
	}
	log.Printf("%d\n", userCreReq.Id)
	log.Printf("%s", userCreReq.Name)
}

func handleRequests() {
	myRouter := mux.NewRouter().StrictSlash(true)
	myRouter.HandleFunc("/user/create", userCreateRequest).Methods("POST")
	log.Fatal(http.ListenAndServe(":8080", myRouter))
}

func main() {
	handleRequests()
}

さいごに

サーバーサイドほんと分からないところでエラーを起こすので失敗するたびに備忘録を残したい
あとpostmanいいですよ~

資料

0
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
0
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?