今日已更新 339 条资讯 | 累计 19899 条内容
关于我们

Building a Simple Task API in Go

Steve Omollo 2026年06月01日 14:44 4 次阅读 来源:Dev.to

Previously, we learned how to send and receive data in Go. Now, we will combine those concepts and build a simple CRUD API. CRUD stands for: C reate R ead U pdate D elete These four operations form the foundation of most backend applications. In this tutorial, we will build a simple task API in Go using only the standar library. By the end, you will understand: how CRUD APIs work how to handle multiple HTTP methods how to store data in memory how to send and receive JSON data how backend APIs manage resources Prerequisites To follow along, you should have: Go installed basic familiarity with Go syntax understanding of the net/http package basic understanding of JSON handling You can confirm if Go is installed by running: go version Step 1 — Create the Project Create a new folder for the project: mkdir go-crud-api cd go-crud-api Now initialize a Go module: go mod init go-crud-api This creates a go.mod file for managing project dependencies. Step 2 — Create the Server File Create a file called main.go . Your project structure should now look like this: go-crud-api/ ├─ go.mod └─ main.go Step 3 — Write the CRUD API Open main.go and add the following code: package main import ( "encoding/json" "net/http" ) type Task struct { ID int `json:"id"` Title string `json:"title"` } var tasks [] Task func tasksHandler ( w http . ResponseWriter , r * http . Request ) { w . Header () . Set ( "Content-Type" , "application/json" ) switch r . Method { case http . MethodGet : json . NewEncoder ( w ) . Encode ( tasks ) case http . MethodPost : var task Task err := json . NewDecoder ( r . Body ) . Decode ( & task ) if err != nil { http . Error ( w , "Invalid JSON" , http . StatusBadRequest ) return } tasks = append ( tasks , task ) json . NewEncoder ( w ) . Encode ( task ) default : http . Error ( w , "Method not allowed" , http . StatusMethodNotAllowed ) } } func main () { http . HandleFunc ( "/tasks" , tasksHandler ) http . ListenAndServe ( ":8080" , nil ) } Now let's unpack what is hap

本文内容来源于互联网,版权归原作者所有
查看原文