加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

golang进阶(五)——restful开发的json处理

发布时间:2020-12-16 09:44:50 所属栏目:大数据 来源:网络整理
导读:前言 restful开发时,对象转json,json转对象是非常频繁的操作,怎么样才能少些重复的代码呢,以这个为目的开启这篇文章 所有代码放在github上 简化数据结构 每次需要返回的数据有code,msg,data这些字段,每个类型都加这些字段太繁复了,这里有interface的方

前言

restful开发时,对象转json,json转对象是非常频繁的操作,怎么样才能少些重复的代码呢,以这个为目的开启这篇文章

所有代码放在github上

简化数据结构

每次需要返回的数据有code,msg,data这些字段,每个类型都加这些字段太繁复了,这里有interface的方式,去代替任意类型,然后使用的时候data字段与其他类型任意的组合

package model

type Resp struct {
    Code string      `json:"code"`
    Msg  string      `json:"msg,omitempty"`
    Data interface{} `json:"data,omitempty"`
}

type User struct {
    Username string `json:"username"`
    Password string `json:"password,omitempty"`
}

json和http请求结合起来

对golang自带的json处理包装,使之可以直接从http请求中读出对象,把对象以json格式输出到响应中

package tools

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)

// MarshalJson 把对象以json格式放到response中
func MarshalJson(w http.ResponseWriter,v interface{}) error {
    data,err := json.Marshal(v)
    if err != nil {
        return err
    }
    fmt.Fprint(w,string(data))
    return nil
}

// UnMarshalJson 从request中取出对象
func UnMarshalJson(req *http.Request,v interface{}) error {
    result,err := ioutil.ReadAll(req.Body)
    if err != nil {
        return err
    }
    json.Unmarshal([]byte(bytes.NewBuffer(result).String()),v)
    return nil
}

调用

经过以上的处理,调用变得相当容易,不需要再做更多的重复编码,代码可读性上大大提高

func UserLoginndler(w http.ResponseWriter,r *http.Request) {
    user := &model.User{}
    tools.UnMarshalJson(r,user)
    resp := &model.Resp{Code: "1001",Msg: "账号或者密码错误"}
    if user.Username == "sweetop" && user.Password == "123456" {
        resp = &model.Resp{Code: "0",Msg: "success"}
    }
    tools.MarshalJson(w,resp)
}
func UserListHandler(w http.ResponseWriter,r *http.Request) {
    resp := &model.Resp{Code: "0",Msg: "success"}
    users := make([]model.User, 0)
    resp.Data = append(users,model.User{Username: "sweetop"})
    tools.MarshalJson(w,resp)
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读