"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Web Service Api Server in Go

Web Service Api Server in Go

Published on 2024-07-31
Browse:519

Web Service Api Server in Go

In this chapter, we will present go and Json web programming to create an API web service with response data types in the form of an API.

  1. WEB Creation API Prepare some sample data first
package main
import "encoding/json"
import "net/http"
import "fmt"
type student struct {
 ID string
 Name string
 Grade int
}
var data = []student{
 student{"E001", "ethan", 21},
 student{"W001", "wick", 22},
 student{"B001", "bourne", 23},
 student{"B002", "bond", 23},
}

The student struct above is used as the sample data slice element type, stored in the data variable.
Next, create a user() function, to handle the /users endpoint. In this function there is a request type detection process via the r.Method() property, to find out whether the request type is Post or Get or something else.

func users(w http.ResponseWriter, r *http.Request) {
 w.Header().Set("Content-Type", "application/json")
 if r.Method == "GET" {
 var result, err = json.Marshal(data)
 if err != nil {
 http.Error(w, err.Error(), http.StatusInternalServerError)
 return
 }
 w.Write(result)
 return
 }
 http.Error(w, "", http.StatusBadRequest)
}

If the request is a GET (retrieve data), then the data is encoded in JSON
used as a response.
The w.Header().Set("Content-Type", "application/json") statement is used for
determine the response type, namely as JSON. While r.Write()
used to register data as a response.
Otherwise, if the request is invalid, the response is set as error using
http.Error() function.
Also set up a handler for the /user endpoint. The difference between this endpoint and
/users above is:
The /users endpoint returns all existing sample data (array).
The /user endpoint returns just one piece of data, taken from the data
sample based on its ID. At this endpoint, the client must send
also the ID information of the data being sought

func user(w http.ResponseWriter, r *http.Request) {
 w.Header().Set("Content-Type", "application/json")
 if r.Method == "GET" {
 var id = r.FormValue("id")
 var result []byte
 var err error
 for _, each := range data {
 if each.ID == id {
 result, err = json.Marshal(each)
 if err != nil {
 http.Error(w, err.Error(), http.StatusInternalServerError)
 return
 }
 w.Write(result)
 return
 }
 }
 http.Error(w, "User not found", http.StatusNotFound)
 return
 }
 http.Error(w, "", http.StatusBadRequest)
}

The r.FormValue() method is used to retrieve form data sent from
client, in this context the data referred to is ID.
By using this ID, relevant data is searched for. If there is, then
returned as a response. If not there then error 400, Bad Request
returned with the message User Not Found.
Finally, implement the two handlers above.

func main() {
 http.HandleFunc("/users", users)
 http.HandleFunc("/user", user)
 fmt.Println("starting web server at http://localhost:8080/")
 http.ListenAndServe(":8080", nil)
}

Run the program, now the web server is live and the data can be consumed.

Release Statement This article is reproduced at: https://dev.to/sukmarizki04/web-service-api-server-in-go-efl?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3