サーバサイド言語はまるで素人なため、ポインタなどの概念が未だうまく捕らえられていません。
加えて、フロントサイドで使わないような複雑な型変換などが多く、つまずいています。
go
1type Items struct { 2 Title string `json:"title"` 3 Content string `json:"content"` 4 Status string `json:"status"` 5 Categories [1]int `json:"categories"` 6}
go
1title := "title" 2content := "<div>content</div>" 3status := "publish" 4categories := [1]int{1} 5 6items := Items{Title: title, Content: content, Status: status, Categories: categories} 7json, err := json.Marshal(&items) 8if err != nil { 9 fmt.Print("json parce error") 10} 11body := []byte(json) 12 13// Post 14req, err := http.NewRequest( 15 "POST", 16 API_URL, 17 bytes.NewBuffer(data), 18) 19if err != nil { 20 fmt.Println("url scarapping failed") 21} 22 23// Content-Type 設定 24req.Header.Set("Content-Type", "application/json") 25req.SetBasicAuth(USER, PASS) 26 27client := &http.Client{} 28resp, err := client.Do(req) 29if err != nil { 30 fmt.Println(err) 31} 32fmt.Println(resp) 33defer resp.Body.Close()
構造体作って、jsonにして、とか全体の流れはわかるのですが、
json.Marshal(&items)
[]byte(json)
bytes.NewBuffer(body)
は何のためにしているのかなどがよくわかりません。
ご教授お願いします。
------ 追記 -------
全行です↓
go
1package main 2 3import ( 4 "bytes" 5 "encoding/json" 6 "fmt" 7 "net/http" 8) 9 10type Items struct { 11 Title string `json:"title"` 12 Content string `json:"content"` 13 Status string `json:"status"` 14 Categories [1]int `json:"categories"` 15} 16 17func main() { 18 const URL = "https://example.com/wp-json/wp/v2/posts/" 19 const USER = "ユーザ" 20 const PASS = "パス" 21 items := Items{Title: "title from api2", Content: "content from api", Status: "publish", Categories: [1]int{1}} 22 23 json, err := json.Marshal(&items) 24 if err != nil { 25 fmt.Print("json parce error") 26 } 27 data := []byte(json) 28 29 // Post 30 req, err := http.NewRequest( 31 "POST", 32 URL, 33 bytes.NewBuffer(data), 34 ) 35 if err != nil { 36 fmt.Println("url scarapping failed") 37 } 38 39 // Content-Type 設定 40 req.Header.Set("Content-Type", "application/json") 41 req.SetBasicAuth(USER, PASS) 42 client := &http.Client{} 43 resp, err := client.Do(req) 44 if err != nil { 45 fmt.Println(err) 46 } 47 fmt.Println(resp) 48 defer resp.Body.Close() 49} 50
何をしたい処理ですか?
data := bytes.NewBuffer(body)
のdataは何に使うんでしょうか?
その後のコードもないので判断できません。
目的がわからないと、何のためにしている処理か答えようがないです。
修正依頼ありがとうございます。
追記いたしました。
まず、下記の部分コンパイル通りますか?
req, err := http.NewRequest(
"POST",
API_URL,
bytes.NewBuffer(data),
)
NewRequestの第三引数の型が違うような気がするんですが。
API_URLも中身定義されてないように思うのですが未定義エラー出ないでしょうか?
書き方が悪かったです。
> NewRequestの第三引数の型が違うような気がするんですが。
現状の型はどうなっているのか。望ましい型を教えていただけるとありがたいです。
コンパイルエラーは出ません。
> API_URLも中身定義されてないように思う
色々端折っちゃったので、全行載せますね。
回答1件
あなたの回答
tips
プレビュー