初学golang,尝试用gin框架搭建restapi
一)源码准备
创建go.mod文件,相当于nodejs中的package.json
go mod init examples/web-service-gin
新建文件main.go,加入以下代码
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
// album represents data about a record album.
type album struct {
ID string `json:"id"`
Title string `json:"title"`
Artist string `json:"artist"`
Price float64 `json:"price"`
}
// albums slice to seed record album data.
var albums = []album{
{ID: "1", Title: "Blue Train", Artist: "John Coltrane", Price: 56.99},
{ID: "2", Title: "Jeru", Artist: "Gerry Mulligan", Price: 17.99},
{ID: "3", Title: "Sarah Vaughan and Clifford Brown", Artist: "Sarah Vaughan", Price: 39.99},
}
// getAlbums responds with the list of all albums as JSON.
func getAlbums(c *gin.Context) {
c.IndentedJSON(http.StatusOK, albums)
}
func main() {
router := gin.Default()
router.GET("/albums", getAlbums)
router.Run("localhost:8080")
}
二)安装依赖
go get .
安装完成后,可以在C:\Users[用户名]\go\pkg\mod 下看到相关依赖包
三)运行项目
go run .
运行启动后在浏览器中访问
http://localhost:8080/albums
参考:https://go.dev/doc/tutorial/web-service-gin
标签:album,Title,restapi,golang,json,go,gin,albums From: https://www.cnblogs.com/Andy1982/p/17997240