Go踩坑记录
go http cookie
参考:
https://colobu.com/2018/09/28/cookie-and-session-in-go/
https://researchlab.github.io/2016/07/10/go-setcookie/
https://dzone.com/articles/efficient-multi-threaded-geo-web-crawler-using-jav
https://github.com/PuerkitoBio/gocrawl
https://github.com/ddliu/go-httpclient
https://stackoverflow.com/questions/12130582/setting-cookies-with-net-http
https://github.com/gocolly/colly
/*------------------------------------------分割线----------------------------------------------*/
为什么用Go呢,只需要处理一个post请求的http服务,感觉用java/php/node都麻烦了,用c++写也麻烦,go的话编出来也是个小巧的程序,很迷你;
问题一:
type Message struct {
title string `json:"title"`
content string `json:"title"`
}
err = json.Unmarshal([]byte(), &msg)
err != nil {
http.Error(w, err.Error(), )
}
fmt.Println(msg.title+","+msg.content)
json解析没有错误但是后面的打印都是空串
后来看到一个答案:https://gocn.vip/question/1405 首字母大写
type Message struct {
Title string `json:"title"`
Content string `json:"title"`
}
果然,打印出预期了-->额
问题二:
this.http.post('http://127.0.0.1:9333' ,JSON.stringify(product),{headers}).subscribe(..)
带{headers}时会导致Unmarshal失败,头先发了一次,头不是json结构,去掉{headers}后正常
/*-----------------------------公司电脑装了个go环境----------------------------------------------*/
https://blog.csdn.net/SMonkeyKing/article/details/86886090
https://gobyexample.com/hello-world+&cd=1&hl=en&ct=clnk&gl=sg
上一个完整测试代码:
package main import ( "encoding/json" "fmt" "io/ioutil" "net/http" ) func main() { http.HandleFunc("/", home) http.ListenAndServe(":9333", nil) } type Message struct { Title string `json:"title"` Content string `json:"content"` } func home(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") //允许访问所有域 w.Header().Add("Access-Control-Allow-Headers", "X-Requested-With, Content-Type,Origin, Authorization, Accept, Client-Security-Token, Accept-Encoding, X-Auth-Token, content-type") //header的类型 w.Header().Set("content-type", "application/json") //返回数据格式是json w.Header().Add("Access-Control-Allow-Methods","GET, POST, PUT, PATCH, POST, DELETE, OPTIONS"); fmt.Fprintf(w, "welcome to yanzi travel") b, err := ioutil.ReadAll(r.Body) //fmt.Println("b="+string(b)) defer r.Body.Close() if err != nil { fmt.Println("b is null"); http.Error(w, err.Error(), 500) return } var msg Message//:= make(map[string]interface{}) err = json.Unmarshal(b, &msg) if err != nil { fmt.Println("json.Unmarshal"); http.Error(w, err.Error(), 500) return } err = ioutil.WriteFile("xxx/"+msg.Title+".xx", []byte(msg.Content), 0644) if err != nil { panic(err) } w.Write([]byte("[123]")) }
- 点赞
- 收藏
- 关注作者
评论(0)