长期更新导致的。我从来没有觉得写golang是一件开心的事情。
Gin实现简单的RESTful API
参考官方给出的教程实现https://go.dev/doc/tutorial/web-service-gin
整体代码:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 
 | type blog struct {Title  string `json:"title"`
 Length int    `json:"length"`
 Date   string `json:"date"`
 }
 
 var blogs = []blog{
 {Title: "Go", Length: 4000, Date: "04-16"},
 {Title: "Python", Length: 5000, Date: "04-22"},
 }
 
 func getBlogs(c *gin.Context) {
 
 c.IndentedJSON(http.StatusOK, blogs)
 }
 
 func postBlogs(c *gin.Context) {
 var newBlog blog
 
 if err := c.BindJSON(&newBlog); err != nil {
 fmt.Println(err)
 return
 }
 blogs = append(blogs, newBlog)
 c.JSON(http.StatusOK, newBlog)
 }
 func main() {
 router := gin.Default()
 router.GET("/blog", getBlogs)
 router.POST("/blog", postBlogs)
 router.Run("localhost:8080")
 }
 
 | 
struct中的变量最后面的字符串,指定了转换成json时的key。go有两种形式表示字符串,一种是",另一个就是`,这样字符串内部的"就不需要转义了。
值得一提的是,如果是Windows环境,使用curl传递json数据,里面的"需要转义。
| 12
 
 | curl -X POST http://localhost:8080/blog -H "Content-Type: application/json" -d "{\"title\":\"Java\",\"length\":1000,\"date\":\"05-01\"}"
 
 | 
字符串处理
go的string是只读的,可以转换成[]byte来进行修改,strings库实现了一些高级操作:
查找
| 12
 3
 
 | s := "it is my go"fmt.Println(strings.Index(s, "go"))
 fmt.Println(strings.Index(s, "og"))
 
 | 
输出:
替换
| 1
 | fmt.Println(strings.Replace(s, "my", "your", 1))
 | 
切分
| 12
 
 | parts := strings.Split(s, " ")fmt.Println(parts)
 
 | 
修剪
| 12
 
 | s2 := "   go lang  "fmt.Println(strings.Trim(s2, " "))
 
 |