怎么用go写api?

简介: 怎么用go写api?

简单http


服务端


golang中,实现一个普通的http接口可以处理get请求和x-www-form-urlencoded类型的post请求,而如果想实现处理json数据的post请求,则需要用另外的方式实现,接收的参数要从request.Body中读取:

import (
    "net/http"
    "encoding/json"
    "log"
)
func main()  {
    http.HandleFunc("/login1", login1)
    http.HandleFunc("/login2", login2)
    http.ListenAndServe("0.0.0.0:8080", nil)
}
type Resp struct {
    Code    string `json:"code"`
    Msg     string `json:"msg"`
}
type  Auth struct {
    Username string `json:"username"`
    Pwd      string   `json:"password"`
}
//post接口接收json数据
func login1(writer http.ResponseWriter,  request *http.Request)  {
    var auth Auth
    if err := json.NewDecoder(request.Body).Decode(&auth); err != nil {
        request.Body.Close()
        log.Fatal(err)
    }
    var result  Resp
    if auth.Username == "admin" && auth.Pwd == "123456" {
        result.Code = "200"
        result.Msg = "登录成功"
    } else {
        result.Code = "401"
        result.Msg = "账户名或密码错误"
    }
    if err := json.NewEncoder(writer).Encode(result); err != nil {
        log.Fatal(err)
    }
}
//接收x-www-form-urlencoded类型的post请求或者普通get请求
func login2(writer http.ResponseWriter,  request *http.Request)  {
    request.ParseForm()
    username, uError :=  request.Form["username"]
    pwd, pError :=  request.Form["password"]
    var result  Resp
    if !uError || !pError {
        result.Code = "401"
        result.Msg = "登录失败"
    } else if username[0] == "admin" && pwd[0] == "123456" {
        result.Code = "200"
        result.Msg = "登录成功"
    } else {
        result.Code = "203"
        result.Msg = "账户名或密码错误"
    }
    if err := json.NewEncoder(writer).Encode(result); err != nil {
        log.Fatal(err)
    }
}
客户端


golang的标准api中用于http客户端请求的主要有三个api : http.Get,http.Post,http.PostForm,其区别如下:



api 作用
http.Get 发送get请求
http.Post post请求提交指定类型的数据
http.PostForm post请求提交application/x-www-form-urlencoded数据


在使用http客户端api的时候要注意一个问题:请求地址的url必须是带http://协议头的完整url,不然请求结果为空。

package main
import (
    "net/http"
    "fmt"
    "io/ioutil"
    "net/url"
    "encoding/json"
    "bytes"
)
type  auth struct {
    Username string `json:"username"`
    Pwd      string   `json:"password"`
}
func main()  {
    get()
    postWithJson()
    postWithUrlencoded()
}
func get()  {
    //get请求
    //http.Get的参数必须是带http://协议头的完整url,不然请求结果为空
    resp, _ := http.Get("http://localhost:8080/login2?username=admin&password=123456")
    defer resp.Body.Close()
    body, _ := ioutil.ReadAll(resp.Body)
    //fmt.Println(string(body))
    fmt.Printf("Get request result: %s\n", string(body))
}
func postWithJson()  {
    //post请求提交json数据
    auths := auth{"admin","123456"}
    ba, _ := json.Marshal(auths)
    resp, _ := http.Post("http://localhost:8080/login1","application/json", bytes.NewBuffer([]byte(ba)))
    body, _ := ioutil.ReadAll(resp.Body)
    fmt.Printf("Post request with json result: %s\n", string(body))
}
func postWithUrlencoded()  {
    //post请求提交application/x-www-form-urlencoded数据
    form := make(url.Values)
    form.Set("username","admin")
    form.Add("password","123456")
    resp, _ := http.PostForm("http://localhost:8080/login2", form)
    body, _ := ioutil.ReadAll(resp.Body)
    fmt.Printf("Post request with application/x-www-form-urlencoded result: %s\n", string(body))


beego框架


有人评论我就更新


引用


golang实现get和post请求的服务端和客户端

相关文章
|
11天前
|
存储 关系型数据库 Go
【Go语言专栏】基于Go语言的RESTful API开发
【4月更文挑战第30天】本文介绍了使用Go语言开发RESTful API的方法,涵盖了路由、请求处理、数据存储和测试关键点。RESTful API基于HTTP协议,无状态且使用标准方法表示操作。在Go中,通过第三方库如`gorilla/mux`进行路由映射,使用`net/http`处理请求,与数据库交互可选ORM库`gorm`,测试则依赖于Go内置的`testing`框架。Go的简洁性和并发性使得它成为构建高效API的理想选择。
|
22天前
|
API Go
使用Go语言通过API获取代理IP并使用获取到的代理IP
使用Go语言通过API获取代理IP并使用获取到的代理IP
|
6月前
|
JSON 监控 测试技术
RESTful API设计与实现在员工行为监控系统中的数据交互接口(Go语言)
在现代企业环境中,对员工行为进行监控已经成为确保组织安全和合规性的重要手段。为了提高监控系统的效率和可靠性,自动化测试在系统开发过程中发挥着关键作用。本文将探讨在员工行为监控系统开发中采用JUnit进行自动化测试的实际应用,并通过代码示例演示其工作原理。
194 1
|
7月前
|
关系型数据库 MySQL API
Go语言微服务框架 - 6.用Google风格的API接口打通MySQL操作
随着RPC与MySQL的打通,整个框架已经开始打通了数据的出入口。 接下来,我们就尝试着实现通过RPC请求操作MySQL数据库,打通整个链路,真正地让这个平台实现可用。
19 0
|
10月前
|
JavaScript 前端开发 Go
Go WASM:如何在 Go 中访问 DOM API?
Go WASM:如何在 Go 中访问 DOM API?
147 0
|
11月前
|
安全 Java 编译器
如何用 Go 调用 Windows API | 青训营笔记
如何用 Go 调用 Windows API | 青训营笔记
837 0
|
12月前
|
JavaScript Java 程序员
【chatgpt】openai api 接口调用(go语言版)
【chatgpt】openai api 接口调用(go语言版)
799 0
|
JSON API Go
go语言实现调用阿里云api,获取hostname和ip字段值,输出exl表
go语言实现调用阿里云api,获取hostname和ip字段值,输出exl表
257 0
go语言实现调用阿里云api,获取hostname和ip字段值,输出exl表
|
缓存 NoSQL Go
Go对接三方API实践
今天这篇分享:使用Go语言对接三方API实践。
334 0
|
XML 编解码 JSON
GO 语言标准库 API | 学习笔记
快速学习 G0 语言标准库 API
741 0
GO 语言标准库 API | 学习笔记