golang原生api实现get和post

服务端

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

getpost.go

package main

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,不然请求结果为空。

getpostclient.go

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))
}

运行getpost.go后再运行getpostclient输出结果如下:

Get request result: {"code":"200","msg":"登录成功"}

Post request with json result: {"code":"200","msg":"登录成功"}

Post request with application/x-www-form-urlencoded result: {"code":"200","msg":"登录成功"}

Process finished with exit code 0

原文地址:https://www.cnblogs.com/cord/p/9571960.html

时间: 2024-08-30 03:02:58

golang原生api实现get和post的相关文章

ZooKeeper实现配置中心的实例(原生API实现)(转)

说明:要实现配置中心的例子,可以选择的SDK有很多,原生自带的SDK也是不错的选择.比如使用I0Itec,Spring Boot集成等. 大型应用通常会按业务拆分成一个个业务子系统,这些大大小小的子应用,往往会使用一些公用的资源,比如:需要文件上传.下载时,各子应用都会访问公用的Ftp服务器.如果把Ftp Server的连接IP.端口号.用户名.密码等信息,配置在各子应用中,然后这些子应用再部署到服务器集群中的N台Server上,突然有一天,Ftp服务器要换IP或端口号,那么问题来了?),而是如

ZooKeeper客户端原生API的使用以及ZkClient第三方API的使用

这两部分内容的介绍主要讲的是节点及节点内容和子节点的操作,并且讲解的节点的事件监听以及ACL授权 ZooKeeper客户端原生API的使用 百度网盘地址: http://pan.baidu.com/s/1jI3b8n8 ZkClient第三方API的使用 ZkClient是Github上一个开源的ZooKeeper客户端.ZkClient在ZooKeeper原生API之上进行了包装,是一个更加易用的ZooKeeper客户端.同时ZkClient在内部实现了诸如Session超时重连.Watche

(原) 2.1 Zookeeper原生API使用

本文为原创文章,未经允许不得转载 Zookeeper原生API使用 1.jar包引入,演示版本为3.4.6,非maven项目,可以下载jar包导入到项目中 <dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> <version>3.4.6</version> </dependency> 2.

ios网络学习------11 原生API文件上传之断点续传思路

#import "MainViewController.h" @interface MainViewController () @end @implementation MainViewController - (void)viewDidLoad { [super viewDidLoad]; //下载文件 [self download]; } -(void)download { //1. NSURL NSURL *url = [NSURL URLWithString:@"ht

使用IOS7原生API进行二维码条形码的扫描

使用IOS7原生API进行二维码条形码的扫描 IOS7之前,开发者进行扫码编程时,一般会借助第三方库.常用的是ZBarSDK,IOS7之后,系统的AVMetadataObject类中,为我们提供了解析二维码的接口.经过测试,使用原生API扫描和处理的效率非常高,远远高于第三方库. 一.使用方法示例 官方提供的接口非常简单,代码如下: ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30

springmvc使用pojo和servlet原生api作为参数

一.Pojo作为参数: 实体: package com.hy.springmvc.entities; public class User { private String username; private String password; private String email; private Address address; public String getUsername() { return username; } public void setUsername(String us

Spring MVC 使用Servlet原生API作为参数

具体看代码: 1 @RequestMapping("/testServletAPI") 2 public void testServletAPI(HttpServletRequest request, 3 HttpServletResponse response,HttpSession session, 4 Write r out) throws IOException{ 5 System.out.println(request); 6 System.out.println(respo

phonegap+cordova+ionic调用原生API

上一篇博客讲了phonegap+cordova+ionic的环境搭建,今天再来分享一篇cordova调用原生API的文章.从技术角度上来讲,这并不是很难,只是有些细节要是没有注意,或者某些步骤不知道的,那么在坑里一时半会很难爬出来.所以这两篇博客旨在帮助小伙伴们节省更多的时间去做其他有意义的事情. 1.新建工程 新建工程和添加平台支持的操作已经在上一篇博客中讲到了, 这里不再赘述. 2.Bower的使用 首先确认是否安装了bower,如果没有安装,打开cmd命名,输入npm install -g

微软发布WP SDK8.0 新增语音、应用内支付等原生API

http://www.csdn.net/article/2012-10-31/2811338-windows-phone-8-sdk 京时间10月30日,微软在旧金山举行新一代手机操作系统Windows Phone 8发布会,试图在竞争如此激烈的智能手机市场上多分一杯羹.除了推出新一代的Windows Phone 8外,微软官方表示,开发者还可以下载Windows Phone SDK 8.0. Windows Phone 8新特性: Data Sense.内置Xbox.Live Tiles Wi