はじめに
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いいですよ~