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.
- 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.
Top comments (0)