How to build a RESTful API using Golang and deploy it to Heroku? Steps: Install Go and create a new project. Write the API code and start the local server. Create a Heroku account and install the Heroku CLI. Initialize Heroku, create the application and deploy the code. Access the deployed application and view the response returned.
Build a RESTful API using Golang and deploy to Heroku
Golang is a popular backend programming language known for its high efficiency Known for its ease of use. This tutorial will guide you on how to build a RESTful API using Golang and deploy it to Heroku, a well-known cloud platform.
Build Golang RESTful API
go mod init restful-api
main.go
in your project directory and enter the following code: package main import ( "log" "net/http" "github.com/gorilla/mux" ) func main() { router := mux.NewRouter() router.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Hello, world!")) }) // 监听端口 8080 的请求 log.Fatal(http.ListenAndServe(":8080", router)) }
go run main.go
You should be able to access it in your browser via http://localhost:8080/hello
API.
Deploy to Heroku
heroku init
heroku create restful-api
git push heroku main
heroku open
Practical Case
You can use this RESTful API as the basis for building more complex applications. The following is a practical case showing how to use the API to get data from the database:
func getProducts(w http.ResponseWriter, r *http.Request) { db := ... // 数据库连接 var products []Product err := db.Select(&products, "SELECT * FROM products") if err != nil { log.Println(err) http.Error(w, http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError)) return } json.NewEncoder(w).Encode(products) }
You can also use the API to create, update, and delete data in the database.
The above is the detailed content of How to build a RESTful API using Golang and deploy to Heroku?. For more information, please follow other related articles on the PHP Chinese website!