golang简单高效的JSON读写处理插件库jsonhandlers的使用
Golang简单高效的JSON读写处理插件库jsonhandlers的使用
Jsonhandlers是一个提供简单处理程序的JSON库,可以让你轻松地从各种来源读取和写入JSON。
安装
go get github.com/abusomani/jsonhandlers
使用
Go的import语句的一个非常有用的特性是别名。导入别名的一个常见用例是为库的包名提供更短的替代方案。
在这个例子中,我们使用jh
代替每次调用库函数时输入jsonhandlers
。
import (
jh "github.com/abusomani/jsonhandlers"
)
选项
Jsonhandlers包在创建新的jsonhandler
时公开了多个选项,以便能够从文件、HTTP请求或HTTP响应等来源读取/写入JSON。
WithFileHandler
你可以使用WithFileHandler
选项从文件读取/写入JSON。为此,你需要使用文件处理程序选项创建一个新的jsonhandler。
示例代码
package operations
import (
"fmt"
"github.com/abusomani/jsonhandlers"
)
func handleFile() {
jh := jsonhandlers.New(jsonhandlers.WithFileHandler(testFilePath))
var sch school
err := jh.Unmarshal(&sch)
}
WithHTTPRequestHandler
你可以使用WithHTTPRequestHandler
选项从HTTP请求读取JSON并向HTTP ResponseWriter写入JSON。为此,你需要使用HTTP请求处理程序选项创建一个新的jsonhandler。
示例代码
package operations
import (
"net/http"
"github.com/abusomani/jsonhandlers"
)
type studentSearchRequest struct {
Name string
}
type studentSearchResponse struct {
Info student
}
func HandleHTTPRequest(students []student) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
jh := jsonhandlers.New(jsonhandlers.WithHTTPRequestHandler(w, r))
var reqBody studentSearchRequest
_ := jh.Unmarshal(&reqBody)
for _, student := range students {
// student found
if student.Name == reqBody.Name {
// write the response using jh.Marshal
jh.Marshal(studentSearchResponse{
Info: student,
})
return
}
}
})
}
/*
Sample request to be hit on the localhost server to test WithHTTPRequestHandler functionality.
curl http://localhost:8080/search -d '{"Name": "Abhishek Somani"}'
*/
WithHTTPResponseHandler
你可以使用WithHTTPResponseHandler
选项从HTTP响应读取/写入JSON。为此,你需要使用HTTP响应处理程序选项创建一个新的jsonhandler。
示例代码
package operations
import (
"fmt"
"log"
"net/http"
"github.com/abusomani/jsonhandlers"
)
type user struct {
Id int
FirstName string
LastName string
}
type getUsersResponse struct {
Users []user
}
func HandleHTTPResponse() {
resp, _ := http.Get("https://dummyjson.com/users")
jh := jsonhandlers.New(jsonhandlers.WithHTTPResponseHandler(resp))
var userResp getUsersResponse
jh.Unmarshal(&userResp)
}
运行示例
要运行示例文件夹中的示例,你需要首先通过执行git clone
检出这个包。一旦你检出了这个包,你就可以使用以下命令运行main.go来查看所有示例的运行情况:
go run example/main.go
许可证
根据MIT许可证授权
更多关于golang简单高效的JSON读写处理插件库jsonhandlers的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html