Go - Creating a JSON Web Service API

发布时间 2023-10-17 20:11:36作者: ZhangZhihuiAAA

Problem: You want to create a simple web service API that returns JSON.


Solution: Use the net/http package to create a web service API and the encoding/json package to encode data to be sent back as JSON.

 

You’ll create a web service API that returns a list of people in JSON format. You’ll use the net/http and chi packages to create the web service API and the encoding/json package to encode data to be sent back as JSON. 

Start by creating a Person struct:

type   Person   struct   { 
      Name        string   `json:"name"` 
      Height      string   `json:"height"` 
      Mass        string   `json:"mass"` 
      HairColor   string   `json:"hair_color"` 
      SkinColor   string   `json:"skin_color"` 
      EyeColor    string   `json:"eye_color"` 
      BirthYear   string   `json:"birth_year"` 
      Gender      string   `json:"gender"` 
} 

var   list   [] Person 

func   init ()   { 
      file ,   _   :=   os . Open ( "./datafiles/people.json" ) 
      defer   file . Close () 
      data ,   _   :=   io . ReadAll ( file ) 
      json . Unmarshal ( data ,   & list ) 
}

You use the init function to initialize the list variable with the data from the people.json file. This will be the data that you’ll return as JSON:

[ 
      { 
      "name" :   "Luke  Skywalker" , 
      "height" :   "172" , 
      "mass" :   "77" , 
      "hair_color" :   "blond" , 
      "skin_color" :   "fair" , 
      "eye_color" :   "blue" , 
      "birth_year" :   "19BBY" , 
      "gender" :   "male" 
      }, 
      { 
      "name" :   "C - 3PO" , 
      "height" :   "167" , 
      "mass" :   "75" , 
      "hair_color" :   "n/a" , 
      "skin_color" :   "gold" , 
      "eye_color" :   "yellow" , 
      "birth_year" :   "112BBY" , 
      "gender" :   "n/a" 
      }, 
      { 
      "name" :   "R2 - D2" , 
      "height" :   "96" , 
      "mass" :   "32" , 
      "hair_color" :   "n/a" , 
      "skin_color" :   "white,  blue" , 
      "eye_color" :   "red" , 
      "birth_year" :   "33BBY" , 
      "gender" :   "n/a" 
      } 
]

Now you create a handler that uses the pattern "/people/{id}" to create a RESTful API that uses the path pattern /people/<id> :

func   main ()   { 
      mux   :=   chi . NewRouter () 
      mux . Get ( "/people/{id}" ,   people ) 
      http . ListenAndServe ( ":8000" ,   mux ) 
}

func   people ( w   http . ResponseWriter ,   r   * http . Request )   { 
      w . Header (). Set ( "Content-Type" ,   "application/json" ) 
      idstr   :=   chi . URLParam ( r ,   "id" ) 
      id ,   err   :=   strconv . Atoi ( idstr ) 
      if   err   !=   nil   { 
          w . WriteHeader ( http . StatusBadRequest ) 
          return 
      } 
      if   id   <   0   ||   id   >=   len ( list )   { 
          w . WriteHeader ( http . StatusNotFound ) 
          return 
      } 
      json . NewEncoder ( w ). Encode ( list [ id ]) 
}

First, set the Content - Type header to application/json . This tells the client that the response is in JSON format. Next, get the id from the URL path using the chi.URLParam function. If the id is not a number, you return a 400 Bad Request error. If the id is out of range, you return a 404 Not Found error.