golang实现Http Server

实现Http Server 主要使用golang 的 gin包, 接口使用Post发送, 数据格式采用Json格式,
注意, 定义Json格式时, 变量的首字母,必须大写, 不然会识别失败.

Json格式的解析和打包使用golang的默认json包
打包: json.Marshal()
解包:json.Unmarshal()

Http Server 代码:

package main

import (
    "database/sql"
    "fmt"
    _ "github.com/go-sql-driver/mysql"
    "gopkg.in/gin-gonic/gin.v1"
    "net/http"
    "encoding/json"
    //"reflect"
    "errors"
    "time"
    "strings"
)

var gMysqlIp string = "127.0.0.1"
var gSqlDb *sql.DB

type CustomerInfo struct {
    Id       int        `json:"c_id"`
    Name     string     `json:"c_name"`
}

type DomainInfo struct {
    Id          int     `json:"d_id"`
    Name        string  `json:"d_dname"`
    CustId      int     `json:"d_cust_id"`
    SrcIp       string  `json:"d_src_ip"`
    LogFmt      int     `json:"d_logfmt"`
    LogInterval int     `json:"d_log_interval"`
    LogWild     int     `json:"d_log_wild"`
    Type        int     `json:"d_type"`
    HType       int     `json:"d_htype"`
    LogLevel    int     `json:"d_log_level"`
    BitRate     int     `json:"d_bit_rate"`
    CostWithParent int  `json:"d_cost_with_parent"`
}

type myError struct {
    err   string
    time  time.Time
    count int
}

func (m *myError) Error() string {
    return fmt.Sprintf("%s %d 次。时间:%v", m.err, m.count, m.time)
}

func newErr(s string, i int) *myError {
    return &myError{
        err:   s,
        time:  time.Now(),
        count: i,
    }
}

// 更新域名列表
func UpdateDomain(dm *DomainInfo) error {
    sql := "UPDATE server_conf.domain SET "

    if dm.Id == 0 {
        var err error = errors.New("Message:Id is null!")
        return err
    }

    if dm.Name != "" {
        sql += fmt.Sprintf("d_dname='%v',", dm.Name)
    }

    sql = strings.TrimRight(sql, ",")
    sql += fmt.Sprintf(" WHERE d_id=%v;", dm.Id)
    fmt.Println(sql)

    _, err := gSqlDb.Query(sql)
    if err != nil {
        return err
    }

    return nil
}

func ResponseSuccess(c *gin.Context) {
    c.JSON(http.StatusOK, gin.H{
        "status": gin.H{
            "status_code": http.StatusOK,
            "status":      "ok",
        },
    })
}

func ResponseError(c *gin.Context, err error) {
    fmt.Println(err)
    c.JSON(http.StatusBadRequest, gin.H{
        "status": gin.H{
            "status_code": http.StatusBadRequest,
            "status":      err,
        },
    })
}

func init() {
    fmt.Println("do init")

    var err error
    // 连接mysql
    mysqlConn := fmt.Sprintf("user:passwd@tcp(%v:3600)/server_conf?charset=utf8", gMysqlIp)
    gSqlDb, err = sql.Open("mysql", mysqlConn)
    if err != nil {
        fmt.Printf("connect mysql failed! [%s]", err)
        return
    } else {
        fmt.Println("connect mysql ok!")
    }
}

func main() {
    router := gin.Default()
    router.POST("/updatedomain", func(c *gin.Context) {
        customer := c.DefaultPostForm("customer", "")
        timestamp := c.DefaultPostForm("timestamp", "0")
        param := c.DefaultPostForm("param", "")
        token := c.DefaultPostForm("token", "")

        fmt.Println(customer, timestamp, param, token)

        dm := &DomainInfo{}
        err := json.Unmarshal([]byte(param), &dm)
        if err != nil {
            ResponseError(c, err)
            return
        }

        err = UpdateDomain(dm)
        if err != nil {
            ResponseError(c, err)
            return
        }

        sql := fmt.Sprintf("select d_id, d_dname, d_cust_id from server_conf.domain where d_id=7195;")
        rows, err := gSqlDb.Query(sql)
        if err != nil {
            ResponseError(c, err)
            return
        } else {
            ResponseSuccess(c)
        }

        for rows.Next() {
            var d_id int
            var c_id int
            var d_dname string

            rows.Columns()
            err = rows.Scan(&d_id, &d_dname, &c_id)
            if err != nil {
                fmt.Printf("Get domain info failed! [%s]", err)
            }

        }
    })

    router.Run(":8000")
    defer gSqlDb.Close()
}

Http Client 代码:
Json格式的解析和打包使用golang的默认json包
打包: json.Marshal()
解包:json.Unmarshal()

package main

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

type DomainInfo struct {
    Id          int     `json:"d_id"`
    Name        string  `json:"d_dname"`
    CustId      int     `json:"d_cust_id"`
    SrcIp       string  `json:"d_src_ip"`
    LogFmt      int     `json:"d_logfmt"`
    LogInterval int     `json:"d_log_interval"`
    LogWild     int     `json:"d_log_wild"`
    Type        int     `json:"d_type"`
    HType       int     `json:"d_htype"`
    LogLevel    int     `json:"d_log_level"`
    BitRate     int     `json:"d_bit_rate"`
    CostWithParent int  `json:"d_cost_with_parent"`
}

func httpPost() {
    dm := &DomainInfo{
        Id:   7195,
        Name: "www.qq.com",
        LogFmt: 100,
    }

    b, err := json.Marshal(dm)

    resp, err := http.Post("http://127.0.0.1:8000/updatedomain",
        "application/x-www-form-urlencoded",
        strings.NewReader(fmt.Sprintf("param=%s", b)))
    if err != nil {
        fmt.Println(err)
    }

    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Println(err)
    }

    fmt.Println(string(body))
}

func main() {
    httpPost()
}
阅读更多
版权声明:http://blog.csdn.net/robertkun https://blog.csdn.net/robertkun/article/details/78966853
个人分类: golang
上一篇golang flag示例
下一篇分布式一致性算法-Raft
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭