Preface
由于十分喜欢 golang 的 logo,今天开始正式入坑 golang,同时,也因为后端开发经验十分匮乏,所以多少写点东西补一补:
Plan
打算实现一个便笺,备忘录这种的微信小程序,用户数据存到后端的 db,简要计划如下:
- 以 openid 作为用户唯一标识,通过 openid 查询用户 create 过的记录;
- 每条记录有title,content 和 created time;
- 增加一条限制规则,每个用户每天最多可以提交10条记录,以防恶意占用资源
换取 openid — backend
handler
func getOpenIdHandle(w http.ResponseWriter, r *http.Request) {
// handle the bad request
if r.Method != "GET" {
io.WriteString(w, "405")
}
// store the request body and print it
vars := r.URL.Query()
fmt.Println(vars)
// get the openid with the code that you have received from the front end
// note: your params should be different with mine
var params string = "https://api.weixin.qq.com/sns/jscode2session?yourparams"
resp, err := http.Get(params)
if err != nil {
fmt.Println("get error!")
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("resp error!")
}
// print the response that you have got and store it
fmt.Println(string(body))
var result string = string(body)
// send the response to front end
io.WriteString(w, result)
}
main
func main() {
// bind the handler to the router
http.HandleFunc("/getopenid", getOpenIdHandle)
// listen
err := http.ListenAndServe(":9090", nil)
if err != nil {
log.Fatal(err)
}
}
Backend Completed!
接下来,运行后端程序,开始监听 9090:
go run main.go
换取 openid — frontend
app.js
wx.login({
success: res => {
// res.code should be sent to the backend to get the openid
wx.request({
url: 'http://127.0.0.1:9090/getopenid',
data: {
code: res.code
},
header: {
'content-type': 'application/json'
},
// print it and set it to localStorage
success (res) {
console.log(res.data.openid);
wx.setStorage({
key: 'openid',
data: res.data.openid,
})
}
})
}
})
运行
server:
client:
小程序页面设计
ongoing…