首页 > 其他分享 >Go - Creating a JSON Web Service API

Go - Creating a JSON Web Service API

时间:2023-10-17 20:12:44浏览次数:27  
标签:Web Creating Service people color JSON json id string

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.

 

标签:Web,Creating,Service,people,color,JSON,json,id,string
From: https://www.cnblogs.com/zhangzhihui/p/17770553.html

相关文章

  • FISCO-BCOS[WeBASEUtils工具类]
    packagepriv.pront.PetStore.utils;importcn.hutool.core.lang.Dict;importcn.hutool.http.Header;importcn.hutool.http.HttpRequest;importcn.hutool.http.HttpResponse;importcn.hutool.json.JSONArray;importcn.hutool.json.JSONObject;importcn.hutool.j......
  • Secure Code Warrior C# Basic OWASP Web Top 10 2017 5: Broken Access Control, 6:
    Learntheropesorhoneyourskillsinsecureprogramminghere.Thesechallengeswillgiveyouanunderstandingof5:BrokenAccessControl,6:SecurityMisconfigurationand7:XSSvulnerabilities5:BrokenAccessControl, 6:SecurityMisconfiguration ......
  • Go - Uploading a File to a Web Application
    Problem: Youwanttouploadafiletoawebapplication. Solution: Usethenet/httppackagetocreateawebapplicationandtheiopackagetoreadthefile. UploadingfilesiscommonlydonethroughHTMLforms.YoulearnedthatHTMLformshaveanencty......
  • Util应用框架Web Api开发环境搭建
    要使用Util应用框架开发项目,首先需要搭建合适的开发环境.迈出第一步,对于很多.Net新人可能并不简单.如果你对.Net环境并不熟悉,请尽量按照本文档进行操作.操作系统请安装Windows10以上版本操作系统.你也可以使用MAC操作系统,但需要自行解决开发环境问题.安装VisualSt......
  • javaWeb-MVC 和三层架构(非详解)
    1.MVC模式MVC结构:MVC是一种分层开发的模式其中1.M:Model,业务模型,处理业务2.V:View,视图,界面展示3.C:Controller,控制器,处理请求,调用模型和视图 下面是一张展示流程控制图MVC的好处:1.职责单一,互不影响2.有利于分工协作3.利于维护,利于组件重用2.三层架构1表现层2.业务逻辑......
  • javaweb-jsp脚本总结笔记
    1什么是JSPjsp又叫JavaserveltPage这门技术最大的特点就是,写jsp就像是再写html但是不仅可以写静态页面,而且可以内置Java代码写出动态页面,也就是说可以为用户提供动态数据。总的来说jsp=java+HTML2.JSP快速入门2.1提供对应的驱动包2.1创建对应jsp文件2.2写对应代码......
  • webapi body 参数获取数据
    publicstringHttpPost(){stringstrURL="";DataTabledt=newArichive().GetKEY();stringJsonString=string.Empty;JsonString="{\"appKey\":\""+dt.Rows[......
  • websocket 简易demo
    websocket简易demo网上找的然后写的demo还有一种写法,跟这种写法不同,先记录这一种引入依赖<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></dependency&g......
  • webpack
    一基础概念Webpack是什么?答:现代javascript构建工具,静态资源打包工具什么叫构建?构建就是把我们在开发环境写的代码,转换成生产环境的代码。构建过程应该包括预编译、语法检查、词法检查、依赖处理、文件合并、文件压缩、单元测试、版本管理等Vite利用浏览器支持ESmodu......
  • vue2 + websocket 断线重连 + 实时数据
    一、websocket事件-1打开事件Socket.onopen连接建立时触发-2消息事件Socket.onmessage客户端接收服务端数据时触发-3错误事件Socket.onerror通信发生错误时触发-4关闭事件Socket.onclose连接关闭时触发二、webs......